💾*zip()

JSobjectsbuilt-inGeneratorgenerator functioncompostion ⟩ *zip()

zip a list of iterables into a single generator function.

// ⭐ 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;

💈範例:

// ⭐ 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 ]
// ]

Last updated