All files / array/operator splitInto.ts

100% Statements 17/17
100% Branches 2/2
100% Functions 2/2
100% Lines 15/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 201x 10x 10x 10x 1x   9x 9x 9x 9x 9x 9x 18x 18x 18x   9x      
export const splitInto = <T>(count: number) =>
  (array: T[]): T[][] => {
    const length = array.length;
    if (!length) {
      throw Error('array is empty');
    }
    const numberOfChunks = Math.min(array.length, count);
    const chunkSize = Math.floor(length / numberOfChunks);
    const excess = length % numberOfChunks;
    const result: T[][] = [];
    let start = 0;
    for (let i = 0; i < numberOfChunks; i++) {
      const end = start + chunkSize + +(i < excess);
      result.push(array.slice(start, end));
      start = end;
    }
    return result;
  };