All files / extensions/cornerstone/src/utils interleave.ts

23.52% Statements 4/17
80% Branches 4/5
100% Functions 1/1
26.66% Lines 4/15

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                  16x 1x   15x 15x                                      
/**
 * Interleave the items from all the lists so that the first items are first
 * in the returned list, the second items are next etc.
 * Does this in a O(n) fashion, and return lists[0] if there is only one list.
 *
 * @param lists - Array of arrays to interleave
 * @returns Array reordered to be breadth first traversal of lists
 */
export default function interleave<T>(lists: T[][]): T[] {
  if (!lists || !lists.length) {
    return [];
  }
  if (lists.length === 1) {
    return lists[0];
  }
 
  const useLists = [...lists];
  const ret = [];
  for (let i = 0; useLists.length > 0; i++) {
    for (let j = 0; j < useLists.length; j++) {
      const list = useLists[j];
      Iif (i >= list.length) {
        useLists.splice(j, 1);
        j--; // Adjust index after removal to avoid iterator skipping
        continue;
      }
      ret.push(list[i]);
    }
  }
 
  return ret;
}