Generator Function in JavaScript
Level 4242 keystrokes
Generator functions produce values on demand using yield, enabling lazy iteration.
JavaScript code
// Generator function declared with function*// Produces numbers from start to end1function* range(start, end) { // Loop through the range2 for (let i = start; i <= end; i++) { // yield pauses execution and returns the value3 yield i;4 }5}// Create a generator instance6const gen = range(1, 5);// next() resumes and gets the next yielded value7console.log(gen.next().value);8console.log(gen.next().value);// Spread runs a new generator to the end and collects its values9console.log([...range(1, 3)]);// for...of iterates through all yielded values10for (const n of range(4, 6)) console.log(n);Output
1 2 [ 1, 2, 3 ] 4 5 6
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
(× 12)× 12.× 11;× 8,× 4=× 3{× 2}× 2+× 2[× 1