To solve this problem, we'll use generator in Javascript. A generator is a function that returns (yield) sequence of results instead of a single result.
We define a generator function in JS as:
function* fibonacci(){
// to be implemented
}
We implement the function above as:
function* fibonacci() {
let a = 0, b = 1;
while (true) {
yield a
a = b, b =a +b;
}
}
You can test it like this:
const result = fibonacci()
console.log(result.next().value); //0
console.log(result.next().value); // 1
console.log(result.next().value); // 2
console.log(result.next().value); // 4
console.log(result.next().value); // 8
console.log(result.next().value); //16
Each time you call result.next().value, a new fibonacci number will be returned
samuel
I code and I speak
Biplab Malakar
Senior Software Engineer, JavaScript Developer, MEAN Developer, Node.js Developer, MERN Developer, Hybrid Mobile App Developer and ML Develo
function *fibonaciSeries(){ let first = 0; let second = 0; let third = 0; let i = 0; while(true) { if(i== 0 || i==1) { first = 1; second =1; third = 1; } else { first = second; second = third; third = first + second; } i+=1; yield third; } } fibo = fibonaciSeries(); for(let i=0; i< 10; i++) { val = fibo.next(); console.log(val.value); }You can call infinite loop or call .next() as much you want