parzh / xrange

Python-esque iterator for number ranges
https://npmjs.org/package/xrange
0 stars 0 forks source link

Define `.forEach`, `.some`, and `.every` methods #14

Open parzhitsky opened 4 years ago

parzhitsky commented 4 years ago

Define analogs of .forEach, .some, and .every methods of Array.prototype1.

interface Fn<Result = unknown> {
  (curr: number, count: number, memo?: Memo): Result;
}

interface XRange {
  forEach(fn: Fn, thisArg?: unknown): void;
  some(predicate: Fn<boolean>, thisArg?: unknown): boolean;
  every(predicate: Fn<boolean>, thisArg?: unknown): boolean;
}

.forEach

Fires after each of the iteration; there's no way to manually "stop" it, — it stops either automatically with the end of the range (which means it shouldn't be used with infinite ranges), or when its callback throws. Doesn't fire for non-iterated (read "empty") ranges.

.some

Short-circuited cousin of .forEach. Returns whether at least one of the calculated items fits the logic of predicate; consequently, returns false for non-iterated (read "empty") ranges. For infinite ranges either returns true (when the first fitting item is found), or hangs forever.

.every

Short-circuited cousin of .forEach. Returns whether strictly all of the calculated items fit the logic of predicate; surprisingly, returns true for non-iterated (read "empty") ranges, because of the concept of vacuous truth. For infinite ranges either returns false (when the first unfitting item is found), or hangs forever.

Considerations:


1 – For other methods (like .map of .filter etc.) require using Array.from, or perhaps consider creating separate npm package (@xrange/extras?)

parzhitsky commented 4 years ago

Blacked by parzh/xrange__core#13