Skip to content

2648. Generate Fibonacci Sequence

Description

Write a generator function that returns a generator object which yields theΒ fibonacci sequence.

TheΒ fibonacci sequenceΒ is defined by the relation XnΒ = Xn-1Β + Xn-2.

The first few numbersΒ of the series are 0, 1, 1, 2, 3, 5, 8, 13.

Β 

Example 1:

Input: callCount = 5
Output: [0,1,1,2,3]
Explanation:
const gen = fibGenerator();
gen.next().value; // 0
gen.next().value; // 1
gen.next().value; // 1
gen.next().value; // 2
gen.next().value; // 3

Example 2:

Input: callCount = 0
Output: []
Explanation: gen.next() is never called so nothing is outputted

Β 

Constraints:

  • 0 <= callCount <= 50

Solutions

Solution 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function* fibGenerator(): Generator<number, any, number> {
    let a = 0;
    let b = 1;
    while (true) {
        yield a;
        [a, b] = [b, a + b];
    }
}

/**
 * const gen = fibGenerator();
 * gen.next().value; // 0
 * gen.next().value; // 1
 */

Comments