generator function fibonacci
Generator Function Fibonacci
As a programmer, I have come across the concept of Fibonacci numbers quite often. A Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers.
A generator function is a special type of function that allows us to generate a sequence of values on the fly, rather than computing them all at once and returning them as an array or list.
The generator function for the Fibonacci sequence is quite simple. It involves using the yield
statement to generate each number in the sequence one by one. Here is an example:
function* fibonacci() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const gen = fibonacci();
for (let i = 0; i < 10; i++) {
console.log(gen.next().value);
}
- The
function*
keyword indicates that this is a generator function. - The
yield
keyword generates each number in the sequence. - The
while
loop continues indefinitely, generating values until the program is interrupted. - The
[a, b] = [b, a + b]
syntax is a shorthand way of swapping the values ofa
andb
and updating their values to the next numbers in the sequence.
You can see this code in action here:
There are many other ways to generate Fibonacci numbers in JavaScript, including using recursion or memoization. However, the generator function approach is particularly elegant and efficient, and it allows us to generate the sequence lazily as needed.