Skip to content

Instantly share code, notes, and snippets.

@ecowden
Last active January 18, 2016 17:22
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 ecowden/e80ba6086406dde85498 to your computer and use it in GitHub Desktop.
Save ecowden/e80ba6086406dde85498 to your computer and use it in GitHub Desktop.
Create a JavaScript `iterable` object without the use of generator functions
// 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