Skip to content

Instantly share code, notes, and snippets.

@ecowden
Last active January 18, 2016 21:35
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/749b3ffda4a62f57ca95 to your computer and use it in GitHub Desktop.
Save ecowden/749b3ffda4a62f57ca95 to your computer and use it in GitHub Desktop.
const assert = require('assert')
function* createIncrementingSequence(increment) {
let nextValue = 0
for (let i = 0; i < maxIterations; i++) {
// ↙ 'yield' each value in the iteration.
yield nextValue
nextValue += increment
}
}
// ---------------
// invoking a generator function creates an iterator
let incrementByTwo = createIncrementingSequence(2)
let sum = 0
for (let n of incrementByTwo) {
sum += n
}
assert.equal(sum, 20)
// We can invoke the iterator manually.
// (You rarely need this. Just understand that there's no magic here.)
// (Also note that it's the same contract as the verbose iterable above.)
incrementByTwo = createIncrementingSequence(2)
assert.deepEqual(incrementByTwo.next(), { done: false, value: 0 })
assert.deepEqual(incrementByTwo.next(), { done: false, value: 2 })
assert.deepEqual(incrementByTwo.next(), { done: false, value: 4 })
assert.deepEqual(incrementByTwo.next(), { done: false, value: 6 })
assert.deepEqual(incrementByTwo.next(), { done: false, value: 8 })
assert.deepEqual(incrementByTwo.next(), { done: true, value: undefined })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment