---
description: interleaves the values of a list of iterables
---

# \*interleave()

[JS](../../..) ⟩ [objects](../../../val/obj) ⟩ [built-in](../../../val/builtin) ⟩ [Generator](..) ⟩ [generator function](../func) ⟩ [compostion](../func/compose) ⟩ \*interleave()

{% hint style="success" %}
<mark style="color:purple;">**interleave**</mark> the values of <mark style="color:yellow;">**a list of**</mark> [iterable](../../iterable "mention")s into a <mark style="color:yellow;">**single**</mark> [func](../func "mention").
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
* replit：[interleave(...iterables)](https://replit.com/@pegasusroe/interleaveiterables#interleave.js)

```javascript
// ⭐ interleave()
//  interleaves the values of a list of iterables
function* interleave(...iterables) {

    // iterables -> iterators
    let iterators = iterables.map(it => it[Symbol.iterator]());
    let i = 0;    // index of current iterator

    // while still some iterators
    while (iterators.length > 0) { 
        
        // if last iterator reached, go back to first
        if (i >= iterators.length) i = 0;

        // get next iteration result of current iterator
        let result = iterators[i].next();
        
        if (result.done) {             // if current iterator done,
            iterators.splice(i, 1);    //   • remove it.
        } else {                       // otherwise, 
            yield result.value;        //   • yield the value 
            i += 1;                    //   • go to next iterator.
        }
    }

    // all iterators done
    return;
}

// export
module.exports = interleave;
```

💈範例：

* require： [iterator](../../iterator/iterator "mention"), [integers](integers "mention")

```javascript
// ⭐ import
const Iterator   = require('./Iterator.js');    // extend iterators
const integers   = require('./integers.js');    // integers()
const interleave = require('./interleave.js');  // interleave()
// --------------------------------------------------------------

//                           ⭐ values start taken from here
interleave(               //  ↓
    integers().take(5),   //  0 ,  1 , 2, 3, 4
    "ab",                 // 'a', 'b'
    [0]                   //  0
).toArray()
// [ 0, 'a', 0, 1, 'b', 2, 3, 4]
```
{% endtab %}

{% tab title="👥 相關" %}
* [zip](zip "mention") is <mark style="color:yellow;">**similar**</mark> to but <mark style="color:red;">**different**</mark> from <mark style="color:purple;">**interleave()**</mark>.
* [seq](seq "mention") yields values <mark style="color:yellow;">**sequentially**</mark>.
{% endtab %}

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