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

Sandro Maglione

Sandro Maglione

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.

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)));

👋・Interested in learning more, every week?

Every week I build a new open source project, with a new language or library, and teach you how I did it, what I learned, and how you can do the same. Join me and other 700+ readers.