Last active
January 18, 2016 21:35
-
-
Save ecowden/749b3ffda4a62f57ca95 to your computer and use it in GitHub Desktop.
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
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