Created
February 17, 2017 08:49
-
-
Save maxpert/af8dda104eda8e2c5497f0b98803c5f3 to your computer and use it in GitHub Desktop.
ES6 Iterators
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(...args) { | |
let [start, stop, step] = args | |
if (stop === undefined) { | |
stop = start | |
start = 0 | |
} | |
let direction = start < stop ? 1 : -1 | |
let i = start | |
step = step || (1 * direction) | |
return { | |
[Symbol.iterator]: () => ({ | |
start, | |
stop, | |
step, | |
next() { | |
if (direction > 0 ? i >= stop : i <= stop) { | |
return { done: true } | |
} | |
let j = i | |
i += step | |
return { | |
done: false, | |
value: j | |
} | |
} | |
}) | |
} | |
} | |
for (let i of $range(10)) { | |
console.log("=", i) | |
} | |
for (let i of $range(10, 0)) { | |
console.log("=", i) | |
} | |
for (let i of $range(10, 0, -2)) { | |
console.log("=", i) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment