Define the fib() function, which returns the next Fibonacci number after each call.
The solution should inject only the name of the fib function into the global scope and not create additional properties of the fib function or its properties.
I need the help by using JavaScript, I’m troubling with the solution..
I’ve tried something like this:
let a = 0, b = 1;
return function() {
let next = a;
a = b;
b = next + b;
return next;
};
}
const getNextFib = fib();
and this:
function fib() {
let a = 1, b = 1;
return () => {
let result = a;
a = b;
b = result + b;
return result;
};
}
but none is legit. (it’s like a test for programming lectures)
3
Answers
The best solution for your problem is
closures
.which helps to return the function from the function and the inner function stores the value of the variables of outer function without regards of function call.This fibonacci function is written using closure to generate the Fibonacci series by just calling the function without storing the variables
curr
,prev
in global scope.If you don’t know about closures then go and refer closures
Another possible solution is to use generator function which will yield values on demand. So it’ll look something like this
So everytime you call the next method you’ll get the next yielded value.
Read more about generators
Only one thing in global scope (fib).
No additional functions wrapping fib, the setup is handled by iife.