...

/

Solution Review: Fibonacci Series Index

Solution Review: Fibonacci Series Index

Let’s discuss the solution to the Fibonacci series index problem given in the previous lesson.

We'll cover the following...

Solution

The solution to the “Fibonacci Series Index” is given below.

Press + to interact
'use strict';
const fibonocciSeries = function*(limit) {
let current = 0;
let next = 1;
let index = 0;
yield *[[index++, current], [index++, next]];
while(true) {
const temp = current;
current = next;
next = next + temp;
yield [index++, next];
if (index > limit) break;
}
}
console.log("For limit = 2");
for(const [index, value] of fibonocciSeries(2)) {
process.stdout.write(value + ", ");
}
console.log('\n'+ "For limit = 4");
for(const [index, value] of fibonocciSeries(4)) {
process.stdout.write(value + ", ");
}
console.log('\n'+ "For limit = 8");
for(const [index, value] of fibonocciSeries(8)) {
process.stdout.write(value + ", ");
}
console.log('\n'+ "For limit = 12");
for(const [index, value] of fibonocciSeries(12)) {
process.stdout.write(value + ", ");
}

Explanation

We need to implement an infinite loop in the generator function that will produce Fibonacci numbers until it reaches the specific condition and breaks the loop.

  • In the Fibonacci series, every subsequent number is the sum of the two previous numbers. So, first, we need to set two starting points, which are ...