💾*fibonacci()
generate fibonacci numbers: 1, 1, 2, 3, 5, 8 ...
JS⟩ iteration ⟩ custom generators ⟩ *fibonacci()
💾 replit:fibonacci sequence
🌀 extension: Iterator - extend built-in iterable iterators.
// ⭐️ fibonacci sequence: 1, 1, 2, 3, 5, 8 ... (generator)
// -------------------------------------------------------
function* fibonacci() {
let [prev, next] = [0, 1]; // ⭐️ destructuring assignment
// ⭐️ infinite if `terms` is `undefined`, finite otherwise.
while (true) {
yield next;
[prev, next] = [next, prev + next];
}
}
// ⭐️ nth term of Fibonacci sequence
// -------------------------------------------------------
function F(n) {
// return 0 if !(n > 0)
if (!(n > 0)) return 0;
// iterate sequence until we get to the nth term
for (const x of fibonacci()) {
if (--n <= 0) return x;
}
}
// ⭐️ export
module.exports = { fibonacci, F }
Last updated
Was this helpful?