Last active
December 25, 2023 19:47
-
-
Save jaquinocode/afdbbe17e4306238d293c43e90157540 to your computer and use it in GitHub Desktop.
range function for JavaScript. range is a function that's central to Python that I've implemented in JS. Here, it's a generator just like how it is in Python. Works with negative number arguments.
This file contains hidden or 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
function* range(start, stop, step=1) { | |
if(typeof stop === 'undefined') [start, stop] = [0, start] | |
for(let i = start; step > 0 ? i < stop : i > stop; i += step) | |
yield i | |
} | |
/* | |
[...range(0, 10, 2)] | |
[0, 2, 4, 6, 8] | |
[...range(2, 2)] | |
[] | |
[...range(3, -1, -1)] | |
[3, 2, 1, 0] | |
for(let i of range(10)) | |
console.log(i) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment