Hyperlinkv0.8.0-beta.28

Array

Array.chopconsteffect/Array.ts:2610
<S extends Iterable<any>, B>(
  f: (
    as: NonEmptyReadonlyArray<ReadonlyArray.Infer<S>>
  ) => readonly [B, ReadonlyArray<ReadonlyArray.Infer<S>>]
): (self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>
<A, B>(
  self: NonEmptyReadonlyArray<A>,
  f: (as: NonEmptyReadonlyArray<A>) => readonly [B, ReadonlyArray<A>]
): NonEmptyArray<B>
<A, B>(
  self: Iterable<A>,
  f: (as: NonEmptyReadonlyArray<A>) => readonly [B, ReadonlyArray<A>]
): Array<B>

Applies a function repeatedly to consume prefixes of the array and collect the values it produces.

When to use

Use when you need custom grouping logic where each step returns both a value and the remaining input.

Details

The function receives a NonEmptyReadonlyArray and returns [value, rest]. Processing continues until the remaining array is empty.

Example (Chopping an array)

import { Array } from "effect"

const result = Array.chop(
  [1, 2, 3, 4, 5],
  (as): [number, Array<number>] => [as[0] * 2, as.slice(1)]
)
console.log(result) // [2, 4, 6, 8, 10]
Source effect/Array.ts:261030 lines
export const chop: {
  <S extends Iterable<any>, B>(
    f: (as: NonEmptyReadonlyArray<ReadonlyArray.Infer<S>>) => readonly [B, ReadonlyArray<ReadonlyArray.Infer<S>>]
  ): (self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>
  <A, B>(
    self: NonEmptyReadonlyArray<A>,
    f: (as: NonEmptyReadonlyArray<A>) => readonly [B, ReadonlyArray<A>]
  ): NonEmptyArray<B>
  <A, B>(
    self: Iterable<A>,
    f: (as: NonEmptyReadonlyArray<A>) => readonly [B, ReadonlyArray<A>]
  ): Array<B>
} = dual(2, <A, B>(
  self: Iterable<A>,
  f: (as: NonEmptyReadonlyArray<A>) => readonly [B, ReadonlyArray<A>]
): Array<B> => {
  const input = fromIterable(self)
  if (isReadonlyArrayNonEmpty(input)) {
    const [b, rest] = f(input)
    const out: NonEmptyArray<B> = [b]
    let next: ReadonlyArray<A> = rest
    while (internalArray.isArrayNonEmpty(next)) {
      const [b, rest] = f(next)
      out.push(b)
      next = rest
    }
    return out
  }
  return []
})
Referenced by 2 symbols