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 execution
1function* fibonacci(limit) {
// Initialize first two fibonacci numbers using destructuring
2 let [a, b] = [0, 1];
// Continue while current number is within limit
3 while (a <= limit) {
// yield pauses the function and returns the value
// Execution resumes when next() is called
4 yield a;
// Advance: a becomes b, b becomes the sum of the old a and b
5 [a, b] = [b, a + b];
6 }
7}
8
// Create a generator instance with limit 50
9const fib = fibonacci(50);
// Array to collect results
10const result = [];
// for...of iterates over yielded values
11for (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

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

More JavaScript examples at level 5

← JavaScript typing practice