# \*zip()

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [objects](https://lochiwei.gitbook.io/web/js/val/obj) ⟩ [built-in](https://lochiwei.gitbook.io/web/js/val/builtin) ⟩ [Generator](https://lochiwei.gitbook.io/web/js/iteration/generator) ⟩ [generator function](https://lochiwei.gitbook.io/web/js/iteration/generator/func) ⟩ [compostion](https://lochiwei.gitbook.io/web/js/iteration/generator/func/compose) ⟩ \*zip()

{% hint style="success" %} <mark style="color:purple;">**zip**</mark> <mark style="color:yellow;">**a list of**</mark> [iterable](https://lochiwei.gitbook.io/web/js/iteration/iterable "mention")s into a <mark style="color:yellow;">**single**</mark> [func](https://lochiwei.gitbook.io/web/js/iteration/generator/func "mention").
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

* replit：[zip(...iterables)](https://replit.com/@pegasusroe/zipiterable#zip.js)

```javascript
// ⭐ zip()
//  zip a list of iterables into a single generator function.
function* zip(...iterables) {

    // iterables -> iterators
    let iterators = iterables.map(it => it[Symbol.iterator]());
    // iterators -> iteration results
    let results = iterators.map(it => it.next());
    
    let index = 0;

    // while some results not done, yield values
    while (results.some(result => !result.done)) { 
        yield results.map(result => result.value);
        results = iterators.map(it => it.next());
    }

    // all results done
    return;
}

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

💈範例：

* require： [iterator](https://lochiwei.gitbook.io/web/js/iteration/iterator/iterator "mention"), [integers](https://lochiwei.gitbook.io/web/js/iteration/generator/examples/integers "mention")

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

// ⭐ `zip` is like the "transpose" of a matrix
zip(
    integers().take(5),   // 0, 1, 2, 3, 4
    "ab",                 // 'a', 'b'
    [0]                   // 0
).toArray()
// [
//   [ 0, 'a', 0 ],
//   [ 1, 'b', undefined ],
//   [ 2, undefined, undefined ],
//   [ 3, undefined, undefined ],
//   [ 4, undefined, undefined ]
// ]
```

{% endtab %}

{% tab title="👥 相關" %}

* <mark style="color:purple;">**zip()**</mark> is like the [mat.transpose](https://lochiwei.gitbook.io/web/js/val/builtin/arr/matrix-methods/mat.transpose "mention") of a <mark style="color:yellow;">**matrix**</mark>.
* [interleave](https://lochiwei.gitbook.io/web/js/iteration/generator/examples/interleave "mention") is <mark style="color:yellow;">**similar**</mark> to but <mark style="color:red;">**different**</mark> from <mark style="color:purple;">**zip()**</mark> .
  {% endtab %}

{% tab title="📗 參考" %}

* [ ] JavaScript: The Definitive Guide ⟩ 12.3 Generators
  {% endtab %}
  {% endtabs %}
