Last active
March 23, 2023 05:58
-
-
Save westc/87c634889a6619b08037c159b7bbcfa3 to your computer and use it in GitHub Desktop.
Definitions for generator functions range() and irange()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Gives a range of numbers starting with `start` and ending before or at | |
* `boundary` while incrementing each time by `increment`. | |
* @param {number} start | |
* The number at which position to start. | |
* @param {number} boundary | |
* The number at which position to stop (inclusive). | |
* @param {number=} increment | |
* Defaults to `1`. The amount to increment by between each iteration. | |
* @yields {number} | |
* The next value in the range. | |
* @example | |
* console.log([...irange(1, 10)]); // [1,2,3,4,5,6,7,8,9,10] | |
* @example | |
* console.log([...irange(10, 1, -1)]); // [10,9,8,7,6,5,4,3,2,1] | |
*/ | |
function irange(start, boundary, step=1) { | |
return range(start, boundary + step, step); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Gives a range of numbers starting with `start` and ending before `boundary` | |
* while incrementing each time by `increment`. | |
* @param {number} start | |
* The number at which position to start. | |
* @param {number} boundary | |
* The number at which position to stop (non-inclusive). | |
* @param {number=} increment | |
* Defaults to `1`. The amount to increment by between each iteration. | |
* @yields {number} | |
* The next value in the range. | |
* @example | |
* console.log([...range(1, 10)]); // [0,1,2,3,4,5,6,7,8,9] | |
* @example | |
* console.log([...range(10, 1, -1)]); // [10,9,8,7,6,5,4,3,2] | |
*/ | |
function* range(start, boundary, increment=1) { | |
let remaining = Math.ceil((boundary - start) / increment); | |
if (!isFinite(remaining)) remaining = 0; | |
for (; 0 < remaining--; ) { | |
yield start; | |
start += increment; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment