Skip to content

Instantly share code, notes, and snippets.

@maxpert maxpert/sample.js
Created Feb 17, 2017

Embed
What would you like to do?
ES6 Iterators
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
You can’t perform that action at this time.