Skip to content

Array

The Array module provides point-free functions to work with arrays and some utility types for non empty arrays.

Represents a non-empty array type.

import type { NonEmptyArray } from "@jvlk/fp-tsm"
const arr: NonEmptyArray<number> = [1, 2, 3] // valid
// @ts-expect-error
const emptyArr: NonEmptyArray<number> = [] // invalid, will cause a type error

Represents a non-empty readonly array type.

import type { NonEmptyArray } from "@jvlk/fp-tsm"
const arr: ReadonlyNonEmptyArray<number> = [1, 2, 3] // valid
// @ts-expect-error
const emptyArr: ReadonlyNonEmptyArray<number> = [] // invalid, will cause a type error
// @ts-expect-error
arr.push(4) // cannot modify a readonly array

A utilty type to represent any array type, including mutable and immutable arrays, as well as non-empty arrays.

import type { AnyArray, ReadonlyNonEmptyArray, NonEmptyArray } from "@jvlk/fp-tsm"
import { expect } from "@std/expect/expect"
const firstItem = <T>(arr: AnyArray<T>): T => arr[0]
const arr1: Array<number> = [1, 2, 3]
const arr2: ReadonlyArray<number> = [1]
const arr3: ReadonlyNonEmptyArray<number> = [1, 2]
const arr4: NonEmptyArray<number> = [1]
expect(firstItem(arr1)).toBe(1) // works with mutable array
expect(firstItem(arr2)).toBe(1) // works with immutable array
expect(firstItem(arr3)).toBe(1) // works with readonly non-empty array
expect(firstItem(arr4)).toBe(1) // works with non-empty array

Point-free way to get a value from an array by index. Returns an Option type.

import { Array, Option, pipe } from "@jvlk/fp-tsm"
import { expect } from "@std/expect/expect"
expect(pipe([1, 2, 3], Array.at(0))).toEqual(Option.some(1))
expect(pipe([1, 2, 3], Array.at(3))).toEqual(Option.none)

Point-free way to use Array.prototype.map.

import { Array, pipe } from "@jvlk/fp-tsm"
import { expect } from "@std/expect/expect"
const numbers: ReadonlyArray<number> = [1, 2, 3]
const double = (n: number) => n * 2
const result = pipe(
numbers,
Array.map(double)
)
expect(result).toEqual([2, 4, 6])

Point-free way to use Array.prototype.filter. Works as a valid type guard.

import { Array, pipe } from "@jvlk/fp-tsm"
import { expect } from "@std/expect/expect"
const numbers = [1, 2, 3, 4]
const isEven = (n: number) => n % 2 === 0
const result = pipe(
numbers,
Array.filter(isEven)
)
expect(result).toEqual([2, 4])
// Type guard example
const items = [1, "a", 2, "b", 3]
const isNumber = (x: unknown): x is number => typeof x === "number"
const add = (x: number) => x + 1
const onlyNumbers = pipe(
items,
Array.filter(isNumber),
Array.map(add)
)
expect(onlyNumbers).toEqual([2, 3, 4])

Point-free way to find the first element in an array that satisfies a predicate. Returns an Option type.

import { Array, Option, pipe } from "@jvlk/fp-tsm"
import { expect } from "@std/expect/expect"
const isEven = (n: number) => n % 2 === 0
const numbers = [1, 2, 3, 4]
const result = pipe(
numbers,
Array.findFirst(isEven)
)
expect(result).toEqual(Option.some(2))