Skip to content

Instantly share code, notes, and snippets.

@jaquinocode
Last active December 25, 2023 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaquinocode/afdbbe17e4306238d293c43e90157540 to your computer and use it in GitHub Desktop.
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.
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