๐Ÿ’พ*zip()

JS โŸฉ objects โŸฉ built-in โŸฉ Generator โŸฉ generator function โŸฉ compostion โŸฉ *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