💾*interleave()

interleaves the values of a list of iterables

JSobjectsbuilt-inGeneratorgenerator functioncompostion ⟩ *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