LearnFrenzy
Sign in Take a free test

ES6 Features · ES6 Features Coding Problems · Question 6

Infinite Fibonacci generator in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Write an infinite Fibonacci generator and helpers take(n) and takeWhile(test) to print the first 10 numbers and all Fibonacci numbers below 100 that are even.

Solution
main.js
function* fibonacci() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}
function* take(iter, n) { for (const x of iter) { if (n-- <= 0) return; yield x; } }
function* takeWhile(iter, test) { for (const x of iter) { if (!test(x)) return; yield x; } }

console.log([...take(fibonacci(), 10)].join(" "));
console.log([...takeWhile(fibonacci(), (x) => x < 100)].filter((x) => x % 2 === 0));

Output Verified by running it on Node.js

0 1 1 2 3 5 8 13 21 34
[ 0, 2, 8, 34 ]

The generator would run forever, but take and takeWhile stop pulling values, so only as many numbers as needed are ever computed – lazy evaluation.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links