Hyperlinkv0.8.0-beta.28

Array

Array.modifyconsteffect/Array.ts:1961
<A, B, S extends Iterable<A> = Iterable<A>>(
  i: number,
  f: (a: ReadonlyArray.Infer<S>) => B
): (
  self: S
) => Option.Option<ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>>
<A, B, S extends Iterable<A> = Iterable<A>>(
  self: S,
  i: number,
  f: (a: ReadonlyArray.Infer<S>) => B
): Option.Option<ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>>

Applies a function to the element at the specified index safely, returning the updated array in Option.some.

When to use

Use to derive a replacement value from an array element at a specific index while leaving the other elements unchanged.

Details

Returns Option.none() when the index is out of bounds.

Example (Modifying an element)

import { Array } from "effect"

console.log(Array.modify([1, 2, 3, 4], 2, (n) => n * 2)) // Option.some([1, 2, 6, 4])
console.log(Array.modify([1, 2, 3, 4], 5, (n) => n * 2)) // Option.none()
Source effect/Array.ts:196120 lines
export const modify: {
  <A, B, S extends Iterable<A> = Iterable<A>>(
    i: number,
    f: (a: ReadonlyArray.Infer<S>) => B
  ): (self: S) => Option.Option<ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>>
  <A, B, S extends Iterable<A> = Iterable<A>>(
    self: S,
    i: number,
    f: (a: ReadonlyArray.Infer<S>) => B
  ): Option.Option<ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>>
} = dual(3, <A, B>(self: Iterable<A>, i: number, f: (a: A) => B): Option.Option<Array<A | B>> => {
  const arr = Array.from(self)
  if (isOutOfBounds(i, arr)) {
    return Option.none()
  }
  const out: Array<A | B> = arr
  const b = f(arr[i])
  out[i] = b
  return Option.some(out)
})
Referenced by 2 symbols