Hyperlinkv0.8.0-beta.28

Array

Array.insertAtconsteffect/Array.ts:1880
<B>(i: number, b: B): <A>(
  self: Iterable<A>
) => Option.Option<NonEmptyArray<A | B>>
<A, B>(self: Iterable<A>, i: number, b: B): Option.Option<
  NonEmptyArray<A | B>
>

Inserts an element at the specified index safely, returning a new NonEmptyArray wrapped in an Option.

When to use

Use to insert a single element at a specific position in an array.

Details

Valid indices are 0 to length, inclusive. Inserting at length appends.

Example (Inserting at an index)

import { Array } from "effect"

console.log(Array.insertAt(["a", "b", "c", "e"], 3, "d")) // Option.some(["a", "b", "c", "d", "e"])
Source effect/Array.ts:188011 lines
export const insertAt: {
  <B>(i: number, b: B): <A>(self: Iterable<A>) => Option.Option<NonEmptyArray<A | B>>
  <A, B>(self: Iterable<A>, i: number, b: B): Option.Option<NonEmptyArray<A | B>>
} = dual(3, <A, B>(self: Iterable<A>, i: number, b: B): Option.Option<NonEmptyArray<A | B>> => {
  const out: Array<A | B> = Array.from(self) // copy because `splice` mutates the array
  if (i < 0 || i > out.length) {
    return Option.none()
  }
  out.splice(i, 0, b)
  return Option.some(out as any)
})