Hyperlinkv0.8.0-beta.28

MutableList

MutableList.takeNconsteffect/MutableList.ts:619
<A>(self: MutableList<A>, n: number): Array<A>

Takes up to N elements from the beginning of the MutableList and returns them as an array. The taken elements are removed from the list. This operation is optimized for performance and includes zero-copy optimizations when possible.

Example (Taking batches)

import { MutableList } from "effect"

const list = MutableList.make<number>()
MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

console.log(list.length) // 10

// Take first 3 elements
const first3 = MutableList.takeN(list, 3)
console.log(first3) // [1, 2, 3]
console.log(list.length) // 7

// Take more than available
const remaining = MutableList.takeN(list, 20)
console.log(remaining) // [4, 5, 6, 7, 8, 9, 10]
console.log(list.length) // 0

// Take from empty list
const empty = MutableList.takeN(list, 5)
console.log(empty) // []

// Batch processing pattern
const queue = MutableList.make<string>()
MutableList.appendAll(queue, ["task1", "task2", "task3", "task4", "task5"])

while (queue.length > 0) {
  const batch = MutableList.takeN(queue, 2) // Process 2 at a time
  console.log("Processing batch:", batch)
}
elements
export const takeN = <A>(self: MutableList<A>, n: number): Array<A> => {
  if (n <= 0 || !self.head) return []
  n = Math.min(n, self.length)
  if (n === self.length && self.head?.offset === 0 && !self.head.next) {
    const array = self.head.array
    clear(self)
    return array
  }
  const array = new Array<A>(n)
  let index = 0
  let chunk: MutableList.Bucket<A> | undefined = self.head
  while (chunk) {
    while (chunk.offset < chunk.array.length) {
      array[index++] = chunk.array[chunk.offset]
      if (chunk.mutable) chunk.array[chunk.offset] = undefined as any
      chunk.offset++
      if (index === n) {
        self.head = chunk
        self.length -= n
        if (self.length === 0) clear(self)
        return array
      }
    }
    chunk = chunk.next
  }
  clear(self)
  return array
}
Referenced by 4 symbols