All files chunk.ts

100% Statements 13/13
100% Branches 4/4
100% Functions 3/3
100% Lines 13/13

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 408x                                       8x 5x       5x 5x 5x 13x 7x 7x   13x 13x 5x     5x    
import { purry } from './purry';
 
/**
 * Split an array into groups the length of `size`. If `array` can't be split evenly, the final chunk will be the remaining elements.
 * @param array - the array
 * @param size - the length of the chunk
 * @signature
 *    P.chunk(array, size)
 * @signature
 *    P.chunk(size)(array)
 * @example
 *    P.chunk(['a', 'b', 'c', 'd'], 2) // => [['a', 'b'], ['c', 'd']]
 *    P.chunk(['a', 'b', 'c', 'd'], 3) // => [['a', 'b', 'c'], ['d']]
 *    P.chunk(2)(['a', 'b', 'c', 'd']) // => [['a', 'b'], ['c', 'd']]
 *    P.chunk(3)(['a', 'b', 'c', 'd']) // => [['a', 'b', 'c'], ['d']]
 * @category Array, Pipe
 */
export function chunk<T>(array: readonly T[], size: number): readonly T[][];
export function chunk<T>(size: number): (array: readonly T[]) => readonly T[][];
 
export function chunk() {
  return purry(_chunk, arguments);
}
 
function _chunk<T>(array: T[], size: number) {
  const ret: T[][] = [];
  let current: T[] | null = null;
  array.forEach(x => {
    if (!current) {
      current = [];
      ret.push(current);
    }
    current.push(x);
    if (current.length === size) {
      current = null;
    }
  });
  return ret;
}