Immutable arrays with functional operations
Transform collections with map, filter, reduce without mutating the original data
Immutable arrays with functional operations.
List is an immutable collection that wraps arrays and provides functional operations. Every transformation creates a new List, preserving the original data.
import { List } from "functype/list"
// Creating Lists
const nums = List([1, 2, 3, 4, 5])
const empty = List.empty<number>()
const single = List.of(42)
// Basic operations
nums.head // 1
nums.tail // List([2, 3, 4, 5])
nums.size // 5
nums.isEmpty // false
| Method | Description |
|---|---|
List(array) | Create from array |
List.of(...values) | Create from values |
List.empty<T>() | Create empty typed list |
List.range(start, end) | Create range of numbers |
// Map - transform each element
List([1, 2, 3]).map((x) => x * 2) // List([2, 4, 6])
// Filter - keep matching elements
List([1, 2, 3, 4]).filter((x) => x % 2 === 0) // List([2, 4])
// FlatMap - flatten nested results
List([1, 2]).flatMap((x) => List([x, x * 10])) // List([1, 10, 2, 20])
// Fold - reduce to single value
List([1, 2, 3]).foldLeft(0)((acc, x) => acc + x) // 6
// Take and drop
List([1, 2, 3, 4, 5]).take(3) // List([1, 2, 3])
List([1, 2, 3, 4, 5]).drop(2) // List([3, 4, 5])
List([1, 2, 3, 4, 5]).takeWhile((x) => x < 4) // List([1, 2, 3])
// Find and contains
List([1, 2, 3]).find((x) => x > 1) // 2 (or undefined)
List([1, 2, 3]).contains(2) // true
List([1, 2, 3]).exists((x) => x > 2) // true
// Combine
List([1, 2]).concat(List([3, 4])) // List([1, 2, 3, 4])
List([1, 2]).append(3) // List([1, 2, 3])
List([1, 2]).prepend(0) // List([0, 1, 2])
// Group by key
List([1, 2, 3, 4]).groupBy((x) => (x % 2 === 0 ? "even" : "odd"))
// Map { "odd" => List([1, 3]), "even" => List([2, 4]) }
// Sort
List([3, 1, 2]).sorted() // List([1, 2, 3])
List(["b", "a"]).sortBy((s) => s) // List(["a", "b"])
// Distinct
List([1, 2, 2, 3, 3, 3]).distinct() // List([1, 2, 3])
import { Do, $ } from "functype/do"
// Generate all combinations
const result = Do(function* () {
const x = yield* $(List([1, 2]))
const y = yield* $(List(["a", "b"]))
return `${x}${y}`
}) // List(["1a", "1b", "2a", "2b"])
// Performance: 175x faster than nested flatMaps
list.toArray() // Convert to native array
list.toSet() // Convert to Set<A>
list.headOption // Option<A> for first element