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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!