Skip to content
Version

fold

The fold utility reduces an array down to a single value by applying a callback to each pair of adjacent elements — like reduce but without an initial accumulator.

Source Code

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

/**
 * Folds an array down to a single value by applying a callback to each pair of
 * elements (reduce without an initial value).
 *
 * @example
 * ```ts
 * fold([1, 2, 3], (a, b) => a + b) // 6
 * fold([1, 2, 3], (a, b) => a > b ? a : b) // 3
 * fold([{ a: 1 }, { a: 2 }], (a, b) => ({ a: a.a + b.a })) // { a: 3 }
 * fold([], (a, b) => a + b) // undefined
 * fold([1], (a, b) => a + b) // 1
 * ```
 *
 * @param array - The array to fold.
 * @param callback - The function to invoke for each pair of elements.
 * @returns The folded value, or `undefined` if the array is empty.
 *
 * @throws {TypeError} If the first argument is not an array.
 */
export function fold<T>(array: readonly T[], callback: (a: T, b: T) => T): T | undefined {
  assert(isArray(array), IS_ARRAY_ERROR_MSG, {
    args: { array, callback },
    type: TypeError,
  });

  let result = array[0];

  for (let i = 1; i < array.length; i++) {
    result = callback(result, array[i]);
  }

  return result;
}

Features

  • No initial value required: Works directly on the element type.
  • Empty-safe: Returns undefined for empty arrays instead of throwing.
  • Single-element shortcut: Returns the single element directly.

API

ts
function fold<T>(array: readonly T[], callback: (a: T, b: T) => T): T | undefined;

Parameters

  • array: The array to fold.
  • callback: A function applied to each pair (accumulator, current).

Returns

  • The folded result, or undefined if the array is empty.

Throws

  • TypeError: If the first argument is not an array.

Examples

Summing Numbers

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

fold([1, 2, 3, 4, 5], (a, b) => a + b); // 15

Finding the Maximum

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

fold([3, 1, 4, 1, 5, 9], (a, b) => (a > b ? a : b)); // 9

Merging Objects

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

fold([{ a: 1 }, { b: 2 }, { c: 3 }], (acc, cur) => ({ ...acc, ...cur }));
// { a: 1, b: 2, c: 3 }

Edge Cases

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

fold([], (a, b) => a + b); // undefined
fold([42], (a, b) => a + b); // 42

See Also

  • group: Group array elements by a criterion.
  • select: Filter elements by a predicate.