Hyperlinkv0.8.0-beta.28

Chunk

Chunk.chunksOfconsteffect/Chunk.ts:1298
(n: number): <A>(self: Chunk<A>) => Chunk<Chunk<A>>
<A>(self: Chunk<A>, n: number): Chunk<Chunk<A>>

Groups elements in chunks of up to n elements.

When to use

Use to divide a chunk into ordered, non-overlapping chunks with at most n elements each.

Details

The final chunk may contain fewer than n elements. Empty input produces an empty chunk of chunks.

Gotchas

Values of n less than or equal to zero produce singleton chunks.

Example (Splitting into fixed-size chunks)

import { Chunk } from "effect"

const chunk = Chunk.make(1, 2, 3, 4, 5, 6, 7, 8, 9)
const chunked = Chunk.chunksOf(chunk, 3)

console.log(Chunk.toArray(chunked).map(Chunk.toArray))
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

// When length is not evenly divisible
const chunk2 = Chunk.make(1, 2, 3, 4, 5)
const chunked2 = Chunk.chunksOf(chunk2, 2)
console.log(Chunk.toArray(chunked2).map(Chunk.toArray))
// [[1, 2], [3, 4], [5]]
elementssplit
Source effect/Chunk.ts:129818 lines
export const chunksOf: {
  (n: number): <A>(self: Chunk<A>) => Chunk<Chunk<A>>
  <A>(self: Chunk<A>, n: number): Chunk<Chunk<A>>
} = dual(2, <A>(self: Chunk<A>, n: number) => {
  const gr: Array<Chunk<A>> = []
  let current: Array<A> = []
  toReadonlyArray(self).forEach((a) => {
    current.push(a)
    if (current.length >= n) {
      gr.push(fromArrayUnsafe(current))
      current = []
    }
  })
  if (current.length > 0) {
    gr.push(fromArrayUnsafe(current))
  }
  return fromArrayUnsafe(gr)
})
Referenced by 2 symbols