Last active
October 10, 2021 09:23
-
-
Save CMCDragonkai/d431401b761066750275ba286debc954 to your computer and use it in GitHub Desktop.
Generators and Iterators in JavaScript #javascript #typescript
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
function* range(start: number, stop?: number, step = 1): Generator<number> { | |
if (stop == null) { | |
stop = start; | |
start = 0; | |
} | |
for (let i = start; step > 0 ? i < stop : i > stop; i += step) { | |
yield i; | |
} | |
} | |
console.log([...range(0, 10)]); |
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
function *take<T>(g: Iterator<T>, l: number): Generator<T> { | |
for (let i = 0; i < l; i++) { | |
const item = g.next(); | |
if (item.done) return; | |
yield item.value; | |
} | |
} | |
console.log([...take(range(0, 10), 3)]); | |
/** | |
* Take n items from asynchronous iterator | |
*/ | |
async function *takeAsync<T>(g: AsyncIterator<T>, l: number): AsyncGenerator<T> { | |
for (let i = 0; i < l; i++) { | |
const item = await g.next(); | |
if (item.done) return; | |
yield item.value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment