Skip to content
VersionSize

chunk

The chunk utility splits an array or string into smaller pieces (chunks) of a specified size.

Implementation

View Source Code
ts
import { assert } from '../function/assert';
import { isArray } from '../typed/isArray';
import { isString } from '../typed/isString';

// #region ChunkTypes
type ChunkOptions = {
  overlap?: boolean;
  pad?: string;
};

type ChunkResult<T> = (T extends string ? string : T[])[];
// #endregion ChunkTypes

/**
 * Splits an array or string into chunks of a specified size.
 *
 * @example
 * ```ts
 * chunk([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]]
 * chunk("hello", 2) // ["he", "ll", "o"]
 * chunk("hello", 2, { overlap: true }) // [" h", "he", "el", "ll", "lo", "o "]
 * ```
 *
 * @param input - The input array or string to be chunked.
 * @param size - The size of each chunk.
 * @param [options] - Additional options for chunking.
 * @param [options.overlap] -
 * @param [options.pad] -
 *
 * @returns An array of chunks.
 *
 * @throws {RangeError} If the chunk size is invalid.
 * @throws {TypeError} If the input type is invalid.
 */
export function chunk<T>(input: T[] | string, size = 2, options: ChunkOptions = {}): ChunkResult<T> {
  assert(isArray(input as T[]) || isString(input), 'Argument must be an array or string.', {
    args: { input },
    type: TypeError,
  });

  assert(size >= 1, 'Chunk size must be at least 1.', {
    args: { size },
    type: RangeError,
  });

  const { overlap = false, pad = ' ' } = options;

  if (isString(input) && overlap) {
    const padded = pad + input + pad;
    const numChunks = padded.length - size + 1;
    return Array.from({ length: numChunks }, (_, i) => padded.slice(i, i + size)) as ChunkResult<T>;
  }

  return Array.from({ length: Math.ceil(input.length / size) }, (_, i) =>
    input.slice(i * size, i * size + size),
  ) as ChunkResult<T>;
}

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Versatile: Supports both arrays and strings.
  • Overlapping: Optional support for overlapping chunks in strings.
  • Padding: Optional padding for string chunks that don't meet the chunk size.

API

Type Definitions
ts
type ChunkOptions = {
  overlap?: boolean;
  pad?: string;
};

type ChunkResult<T> = (T extends string ? string : T[])[];
ts
function chunk<T>(input: T[] | string, size?: number, options?: ChunkOptions): ChunkResult<T>;

Parameters

  • input: The array or string to be chunked.
  • size: The size of each chunk (default: 2).
  • options: Optional configuration (for strings):
    • overlap: If true, chunks will overlap by one character.
    • pad: Character used to pad the last chunk if it's shorter than size.

Returns

  • An array containing the chunks.

Examples

Array Chunking

ts
import { chunk } from '@vielzeug/toolkit';

const data = [1, 2, 3, 4, 5, 6, 7];

chunk(data, 2); // [[1, 2], [3, 4], [5, 6], [7]]
chunk(data, 3); // [[1, 2, 3], [4, 5, 6], [7]]

String Chunking

ts
import { chunk } from '@vielzeug/toolkit';

chunk('vielzeug', 3); // ['vie', 'lze', 'ug '] (padded with space by default)

// Custom padding
chunk('hello', 2, { pad: '_' }); // ['he', 'll', 'o_']

// Overlapping chunks
chunk('abc', 2, { overlap: true }); // ['ab', 'bc']

Implementation Notes

  • Throws TypeError if input is neither an array nor a string.
  • Throws RangeError if size is less than 1.
  • For arrays, the last chunk may be smaller than size if the total length is not perfectly divisible.

See Also

  • flatten: The inverse operation for arrays.
  • group: Group array elements by a criterion.