Skip to content
VersionSize

substitute

The substitute utility replaces the first element in an array that satisfies a given predicate with a new value. It provides a clean, functional way to perform "find and replace" operations on arrays without mutating the original data.

Implementation

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

/**
 * Replaces the first element in an array that satisfies the provided predicate function with a new value.
 *
 * @example
 * ```ts
 * substitute([1, 2, 3], (n) => n === 2, 4) // [1, 4, 3]
 * ```
 *
 * @param array - The array to search.
 * @param predicate - A function to test each element of the array.
 * @param value - The new value to replace the found element.
 *
 * @return A new array with the replaced value.
 *
 * @throws {TypeError} If the first argument is not an array.
 */
export function substitute<T>(array: T[], predicate: Predicate<T>, value: T): T[] {
  assert(isArray(array), IS_ARRAY_ERROR_MSG, { args: { array }, type: TypeError });

  const index = findIndex(array, predicate);

  if (index === -1) return array;

  return [...array.slice(0, index), value, ...array.slice(index + 1)];
}

substitute.fn = true;

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Short-circuiting: Stops searching as soon as the first match is found.
  • Immutable: Returns a new array with the substitution applied, leaving the original unchanged.
  • Type-safe: Ensures the replacement value matches the array element type.

API

ts
function substitute<T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean, value: T): T[];

Parameters

  • array: The array to process.
  • predicate: A function to test each element. It receives:
    • item: The current element.
    • index: The index of the current element.
    • array: The original array.
  • value: The new value to insert in place of the matched element.

Returns

  • A new array with the substitution performed. If no element matches the predicate, the returned array will be a shallow copy of the original.

Examples

Replacing Primitives

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

const numbers = [1, 2, 3, 4];

// Replace the value 2 with 20
substitute(numbers, (n) => n === 2, 20); // [1, 20, 3, 4]

Updating Objects

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

const users = [
  { id: 1, name: 'Alice', status: 'pending' },
  { id: 2, name: 'Bob', status: 'pending' },
];

// Update Bob's status
const updated = substitute(users, (u) => u.id === 2, { ...users[1], status: 'active' });
/*
[
  { id: 1, name: 'Alice', ... },
  { id: 2, name: 'Bob', status: 'active' }
]
*/

Implementation Notes

  • Throws TypeError if the first argument is not an array.
  • Only the first element that matches the predicate is replaced.
  • If multiple replacements are needed, consider using map instead.

See Also

  • map: Transform all elements in an array.
  • find: Find an element without replacing it.
  • filter: Remove elements based on a condition.