All files index.js

96.82% Statements 61/63
88% Branches 22/25
80% Functions 4/5
96.82% Lines 61/63

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 641x 3x 3x     3x 3x 3x 3x 3x 3x 3x 30x 30x 30x 60x 33x 33x 33x 33x 6x 6x 33x 27x 27x 27x 33x 33x 33x 30x 30x 30x 3x 3x 30x 30x 3x 3x 3x 3x 3x 30x 30x 30x 54x 51x 43x 43x 43x 51x 54x 30x 30x 30x 30x 30x 3x 3x 31x 31x 30x 3x 1x  
module.exports = function interleave(streams, compare) {
  if (!streams.length)
    return function empty(_abort, cb) {
      cb(true);
    };
 
  // for each stream, indicates: 0 = buffer empty, 1 = buffered, 2 = ended
  let state = Array(streams.length).fill(0);
  // for each stream, contains the buffered stream item or the endErr
  let buffer = Array(streams.length).fill(null);
 
  function fillBuffers(cb) {
    if (state.every((s) => s !== 0)) return cb();
    Promise.all(
      streams.map((stream, i) => {
        if (state[i] !== 0) return Promise.resolve();
        else
          return new Promise((resolve) => {
            stream(null, (end, data) => {
              if (end) {
                state[i] = 2;
                buffer[i] = end;
              } else {
                state[i] = 1;
                buffer[i] = data;
              }
              resolve();
            });
          });
      }),
    ).then(cb);
  }
 
  function getNextMin(cb) {
    fillBuffers(() => {
      if (state.every((s) => s === 2)) {
        buffer = null;
        state = null;
        cb(true);
        return;
      }
      let min = null;
      let j = -1;
      for (let i = 0, n = streams.length; i < n; i++) {
        if (state[i] === 1) {
          if (j < 0 || compare(buffer[i], min) < 0) {
            min = buffer[i];
            j = i;
          }
        }
      }
      buffer[j] = null;
      state[j] = 0;
      cb(null, min);
    });
  }
 
  return function interleavedSource(end, cb) {
    if (end) return cb(end);
    if (!state) return cb(true);
    getNextMin(cb);
  };
};