Hyperlinkv0.8.0-beta.28

Array

Array.rotateconsteffect/Array.ts:2494
(n: number): <S extends Iterable<any>>(
  self: S
) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>
<A>(self: NonEmptyReadonlyArray<A>, n: number): NonEmptyArray<A>
<A>(self: Iterable<A>, n: number): Array<A>

Transforms an array by rotating it n steps. Positive n rotates right; negative n rotates left.

When to use

Use when elements should wrap around the end of the array rather than being dropped.

Details

n is rounded to the nearest integer before rotating. The return type preserves NonEmptyArray. Empty arrays, or rotations normalized to 0, return a copy.

Example (Rotating elements)

import { Array } from "effect"

console.log(Array.rotate(["a", "b", "c", "d"], 2)) // ["c", "d", "a", "b"]
elementstakedrop
Source effect/Array.ts:249421 lines
export const rotate: {
  (n: number): <S extends Iterable<any>>(self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>
  <A>(self: NonEmptyReadonlyArray<A>, n: number): NonEmptyArray<A>
  <A>(self: Iterable<A>, n: number): Array<A>
} = dual(2, <A>(self: Iterable<A>, n: number): Array<A> => {
  const input = fromIterable(self)
  if (isReadonlyArrayNonEmpty(input)) {
    const len = input.length
    const m = Math.round(n) % len
    if (isOutOfBounds(Math.abs(m), input) || m === 0) {
      return copy(input)
    }
    if (m < 0) {
      const [f, s] = splitAtNonEmpty(input, -m)
      return appendAll(s, f)
    } else {
      return rotate(self, m - len)
    }
  }
  return []
})