Generator Function in JavaScript
Level 5217 keystrokes
Uses a generator function to create an iterable fibonacci sequence up to a limit.
JavaScript code
// function* declares a generator function// Generators can pause and resume execution1function* fibonacci(limit) { // Initialize first two fibonacci numbers using destructuring2 let [a, b] = [0, 1]; // Continue while current number is within limit3 while (a <= limit) { // yield pauses the function and returns the value // Execution resumes when next() is called4 yield a; // Advance: a becomes b, b becomes the sum of the old a and b5 [a, b] = [b, a + b];6 }7}8 // Create a generator instance with limit 509const fib = fibonacci(50);// Array to collect results10const result = [];// for...of iterates over yielded values11for (const num of fib) {12 result.push(num);13}// Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]14console.log(result);Output
[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]
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.
;× 7(× 6)× 6[× 5]× 5=× 5,× 4{× 3}× 3.× 2