Hyperlinkv0.8.0-beta.28

MutableList

MutableList.filterconsteffect/MutableList.ts:891
<A>(self: MutableList<A>, f: (value: A, i: number) => boolean): void

Filters the MutableList in place, keeping only elements that satisfy the predicate. This operation modifies the list and rebuilds its internal structure for efficiency.

Example (Filtering in place)

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

// Keep only even numbers
MutableList.filter(list, (n) => n % 2 === 0)

console.log(MutableList.takeAll(list)) // [2, 4, 6, 8, 10]

// Filter with index
const indexed = MutableList.make<string>()
MutableList.appendAll(indexed, ["a", "b", "c", "d", "e"])

// Keep elements at even indices
MutableList.filter(indexed, (value, index) => index % 2 === 0)
console.log(MutableList.takeAll(indexed)) // ["a", "c", "e"]

// Real-world example: filtering a log queue
const logs = MutableList.make<{ level: string; message: string }>()
MutableList.appendAll(logs, [
  { level: "INFO", message: "App started" },
  { level: "ERROR", message: "Connection failed" },
  { level: "DEBUG", message: "Cache hit" },
  { level: "ERROR", message: "Timeout" }
])

// Keep only errors
MutableList.filter(logs, (log) => log.level === "ERROR")
console.log(MutableList.takeAll(logs).map((log) => log.message)) // ["Connection failed", "Timeout"]
mutations
export const filter = <A>(self: MutableList<A>, f: (value: A, i: number) => boolean): void => {
  const array: Array<A> = []
  let chunk: MutableList.Bucket<A> | undefined = self.head
  while (chunk) {
    for (let i = chunk.offset; i < chunk.array.length; i++) {
      if (f(chunk.array[i], i)) {
        array.push(chunk.array[i])
      }
    }
    chunk = chunk.next
  }
  self.head = self.tail = {
    array,
    mutable: true,
    offset: 0,
    next: undefined
  }
  self.length = array.length
}
Referenced by 2 symbols