Skip to main content
Back to problems
#2648
Easy JavaScript

Generate fibonacci sequence

83.7% acceptance
Mar 2, 2026
282
31
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.

Solution

TypeScript
Time O(n)
Space O(1)
LeetCode
solution.ts
function* fibGenerator(): Generator<number, any, number> {
  let a = 0,
  b = 1;
  while (true) {
  yield a;
  [a, b] = [b, a + b];
  }
}

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