Last active
February 10, 2018 15:15
-
-
Save chalkpe/b49cb79ea91e3f66702416ae2ce1e85b to your computer and use it in GitHub Desktop.
python range function for js
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
function* range (...args) { | |
if (args.length === 0) throw new Error('too few parameters') | |
if (args.length === 1) args.unshift(undefined) // start = 0, stop | |
const [start = 0, stop, step = 1] = args | |
for (let k = start; (stop - k) * step > 0; k += step) yield k | |
} | |
// [...range(3)] === [0, 1, 2] | |
// [...range(-5, -1)] === [-5, -4, -3, -2] | |
// [...range(42, 32, -2)] === [42, 40, 38, 36, 34] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment