Skip to content

Instantly share code, notes, and snippets.

@luishendrix92
Last active January 31, 2020 19:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luishendrix92/57075ceb18009ba3f1b2a11783d9ac96 to your computer and use it in GitHub Desktop.
Save luishendrix92/57075ceb18009ba3f1b2a11783d9ac96 to your computer and use it in GitHub Desktop.
Cyclic Iterator (with ES6 Generators) and .take()
/*
Say I need to iterate over [1, 2, 3], yielding a value
at a time but once I reach the final value, I want to
keep receiving the values over and over again, making
it a repeated sequence: 1, 2, 3, 1, 2, 3, 1 and so on...
*/
const cyclic = list => (function* () {
while (true) for (let item of list) yield item
}())
let cycled = cyclic([1, 2, 3])
console.log(cycled.next().value)
//> 1
/*
Also, say I want to, from that cyclic iterator, take
a defined amount of values and put them inside an array.
So if have [1, 2, 3] and the next value is 2 (which
the iterator has not yielded yet) and I want to take
4 numbers away, I'll get in return [2, 3, 1, 2]
*/
const take = (cyclic, howMany, taken = []) => {
return howMany?
take(cyclic, howMany - 1, taken.concat(cyclic.next().value)) :
taken
}
console.log(take(cycled, 4))
//> [2, 3, 1, 2]
@Kraloz
Copy link

Kraloz commented Jan 31, 2020

Great example!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment