Last active
January 31, 2020 19:44
-
-
Save luishendrix92/57075ceb18009ba3f1b2a11783d9ac96 to your computer and use it in GitHub Desktop.
Cyclic Iterator (with ES6 Generators) and .take()
This file contains 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
/* | |
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great example!