capypad
0 day streak
javascript / intermediate
Snippet

Custom Iteration Logic with Generators

Generators are functions that can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances. Using the '*' syntax and the 'yield' keyword, you can produce a sequence of values on demand, which is memory efficient for large datasets or custom sequences.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
function* rangeGenerator(start, end, step = 1) {
let current = start;
while (current <= end) {
yield current;
current += step;
}
}
 
for (const num of rangeGenerator(0, 10, 2)) {
console.log(num); // 0, 2, 4, 6, 8, 10
}
Breakdown
1
function* rangeGenerator(...)
The asterisk denotes a generator function which returns an Iterator object.
2
yield current;
Pauses generator execution and returns the current value to the caller.
3
for (const num of rangeGenerator(...))
Uses the built-in iterator protocol to consume values produced by the generator.