Generator Function in JavaScript
Level 5294 keystrokes
Generator functions use yield to pause execution and return values one at a time when next() is called.
JavaScript code
// Define a generator function with asterisk1function* fibonacci() { // Initialize first two Fibonacci numbers2 let prev = 0, curr = 1; // Infinite loop - generator pauses at yield3 while (true) { // Yield current value and pause4 yield curr; // Advance: prev becomes curr, curr becomes prev + curr5 [prev, curr] = [curr, prev + curr];6 }7}// Create generator iterator8const fib = fibonacci();// Get first value (1)9console.log(fib.next().value);// Get second value (1)10console.log(fib.next().value);// Get third value (2)11console.log(fib.next().value);// Get fourth value (3)12console.log(fib.next().value);// Get fifth value (5)13console.log(fib.next().value);Output
1 1 2 3 5
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.
.× 15(× 13)× 13;× 9=× 4,× 3[× 2]× 2{× 2}× 2