javascript / intermediate
Snippet
Custom Iterators with Generators
Generators are functions that can be paused and resumed. They return an iterator object and use the 'yield' keyword to produce a sequence of values over time instead of all at once.
snippet.js
1
2
3
4
5
6
7
8
function* idGenerator() {let id = 1;while (true) {yield `ID-${id++}`;}}const gen = idGenerator();console.log(gen.next().value); // ID-1
Breakdown
1
function* idGenerator() {
The asterisk (*) denotes a generator function.
2
yield `ID-${id++}`;
Pauses execution and returns the specified value to the caller.