Last active
January 18, 2016 17:22
-
-
Save ecowden/e80ba6086406dde85498 to your computer and use it in GitHub Desktop.
Create a JavaScript `iterable` object without the use of generator functions
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
// Gah! | |
// Don’t try to understand all of this. | |
class IncrementingSequence { | |
constructor(increment) { | |
this.increment = increment | |
} | |
// ↙ Iteration function specially named with a “Symbol” defined by the language | |
[Symbol.iterator]() { | |
const maxIterations = 5 | |
let nextValue = 0 | |
let i = 0 | |
let self = this | |
// The iteration function returns an object with a method | |
// ‘next’. `next()` will be called repeatedly when iterating. | |
return { | |
next() { | |
// Each step in the iteration returns an object with a ‘value’ | |
// and a ‘done’ flag | |
let result = { | |
done: i >= maxIterations, | |
value: nextValue | |
} | |
i++ | |
nextValue += self.increment | |
return result | |
} | |
} | |
} | |
// --------------- | |
// We can iterate through our custom iterable with a "for-of" loop, just | |
// like an array. | |
const assert = require('assert') | |
let sum = 0 | |
let incrementByTwo = new IncrementingSequence(2) | |
for (let n of incrementByTwo) { | |
sum += n | |
} | |
assert.equal(sum, 20) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment