๐Ÿ’พ*interleave()

interleaves the values of a list of iterables

JS โŸฉ objects โŸฉ built-in โŸฉ Generator โŸฉ generator function โŸฉ compostion โŸฉ *interleave()

interleave the values of a list of iterables into a single generator function.

// โญ 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;

๐Ÿ’ˆ็ฏ„ไพ‹๏ผš

// โญ 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]

Last updated