Pure function to update elements in array that are equal in Typescript

16 January 2022

1 min read

Web development

This function allows you to update all the elements in a given array that match the given Eq instance.

This is a pure function (without side-effects) based on functional programming using fp-ts.

updateWhere.ts
import * as A from "fp-ts/Array";
import * as Eq from "fp-ts/Eq";
import { flow } from "fp-ts/function";

/**
 * Update an element inside an array using the given instance of `Eq`
 * @param element Element to search in the array
 * @param eq Instance of `Eq` to compare two elements
 * @returns The given array with the element equal to `element` update (if found)
 */
export const updateWhere =
  <T>(element: T, eq: Eq.Eq<T>) =>
  (update: T): ((array: T[]) => T[]) =>
    flow(A.map((t) => (eq.equals(t, element) ? update : t)));