---
description: 'generate fibonacci numbers: 1, 1, 2, 3, 5, 8 ...'
---

# \*fibonacci()

[JS](../../..)⟩ [iteration](../..) ⟩ [custom generators]() ⟩ \*fibonacci()

{% tabs %}
{% tab title="💾 程式" %}
:floppy\_disk: replit：[fibonacci sequence](https://replit.com/@pegasusroe/generator-fibonacci-numbers#index.js)

🌀 extension： [iterator](../../iterator/iterator "mention") - extend built-in [iterable](../../iterator/iterable "mention")s.

```javascript
// ⭐️ 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 }
```
{% endtab %}

{% tab title="💈範例" %}
:floppy\_disk: replit：[fibonacci sequence](https://replit.com/@pegasusroe/generator-fibonacci-numbers#index.js)

🌀 extension： [iterator](../../iterator/iterator "mention") - extend built-in [iterable](../../iterator/iterable "mention")s.

```javascript
//  ⭐️ import
const Iterator = require('./Iterator.js');    // extend (built-in) iterable iterators
const { fibonacci, F } = require('./fibonacci.js');

// log
[
    // ✅ test extension
    fibonacci()            // generator: 1, 1, 2, 3, 5, 8, ...
        .take(5)           // generator: 1, 1, 2, 3, 5
        .map(x => x * x)   // generator: 1, 1, 4, 9, 25
        .toArray(),        // array: [ 1, 1, 4, 9, 25 ]
    
    // ✅ nth terms
    F(1), F(2), F(3), F(4),       // 1, 1, 2, 3
    F(-2), F(-1), F(0),           // 0, 0, 0
    F('foo'),                     // 0
    
].forEach(x => console.log(x));
```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] JavaScript: The Definitive Guide ⟩ 12.3.1 Generator Example
{% endtab %}
{% endtabs %}
