Project: endless Fibonacci
JavaScript · Unit 16: Iterators and generators
- Full plan
- JavaScript
- Project
- 3 exercises
Fibonacci starts at 0 and 1, and from there each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8… The sequence never ends, which is exactly what a generator is good at.
This is the machine that produces it: two variables shuffling along.
let a = 0;
let b = 1;
for (let i = 0; i < 5; i++) {
console.log(a);
const s = a + b;
a = b;
b = s;
}Prints
0 1 1 2 3
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Complete the code
Fill in the blanks so the generator hands over 0, 1, 1 and 2.
2. Write the code
Write the
fib()generator: it hands over the Fibonacci numbers forever, starting at 0 and 1. ThefirstN(n)function below is ready and keeps the firstnof them.3. Write the code
Now write
fibBelow(max): it returns an array with the Fibonacci numbers belowmax, in order. If none of them are, it returns an empty array. Thefib()generator is already written.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.