Hyperlinkv0.8.0-beta.28

Array

Array.intersperseconsteffect/Array.ts:2318
<B>(middle: B): <S extends Iterable<any>>(
  self: S
) => ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>
<A, B>(self: NonEmptyReadonlyArray<A>, middle: B): NonEmptyArray<A | B>
<A, B>(self: Iterable<A>, middle: B): Array<A | B>

Places a separator element between every pair of elements.

When to use

Use to insert a separator between elements, for example when preparing data for display or concatenation.

Details

The return type preserves NonEmptyArray. Empty inputs produce an empty result.

Example (Interspersing a separator)

import { Array } from "effect"

console.log(Array.intersperse([1, 2, 3], 0)) // [1, 0, 2, 0, 3]
elementsjoin
Source effect/Array.ts:231821 lines
export const intersperse: {
  <B>(
    middle: B
  ): <S extends Iterable<any>>(self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>
  <A, B>(self: NonEmptyReadonlyArray<A>, middle: B): NonEmptyArray<A | B>
  <A, B>(self: Iterable<A>, middle: B): Array<A | B>
} = dual(2, <A, B>(self: Iterable<A>, middle: B): Array<A | B> => {
  const input = fromIterable(self)
  if (isReadonlyArrayNonEmpty(input)) {
    const out: NonEmptyArray<A | B> = [headNonEmpty(input)]
    const tail = tailNonEmpty(input)
    for (let i = 0; i < tail.length; i++) {
      if (i < tail.length) {
        out.push(middle)
      }
      out.push(tail[i])
    }
    return out
  }
  return []
})