Hyperlinkv0.8.0-beta.28

Stream

Stream.zipWithPreviousAndNextconsteffect/Stream.ts:3965
<A, E, R>(self: Stream<A, E, R>): Stream<
  [Option.Option<A>, A, Option.Option<A>],
  E,
  R
>

Zips each element with its previous and next values.

Example (Zipping elements with neighbors)

import { Console, Effect, Option, Stream } from "effect"

const program = Effect.gen(function*() {
  const values = yield* Stream.make(1, 2, 3).pipe(
    Stream.zipWithPreviousAndNext,
    Stream.runCollect
  )
  yield* Console.log(values)
})

Effect.runPromise(program)
// Output: [ [Option.none(), 1, Option.some(2)], [Option.some(1), 2, Option.some(3)], [Option.some(2), 3, Option.none()] ]
zipping
Source effect/Stream.ts:396530 lines
export const zipWithPreviousAndNext = <A, E, R>(
  self: Stream<A, E, R>
): Stream<[Option.Option<A>, A, Option.Option<A>], E, R> =>
  mapAccumArray(self, () => ({
    prev: Option.none<A>(),
    current: Option.none<A>()
  }), (acc, arr) => {
    let i = 0
    let current: A
    if (acc.current._tag === "None") {
      i = 1
      current = arr[0]
      acc.current = Option.some(current)
    } else {
      current = acc.current.value
    }
    const pairs = Arr.empty<[Option.Option<A>, A, Option.Option<A>]>()
    for (; i < arr.length; i++) {
      const element = arr[i]
      acc.current = Option.some(element) as Option.Some<A>
      pairs.push([acc.prev, current, acc.current])
      acc.prev = Option.some(current)
      current = element
    }
    return [acc, pairs]
  }, {
    onHalt(acc) {
      return acc.current._tag === "Some" ? [[acc.prev, acc.current.value, Option.none<A>()]] : []
    }
  })