Options
All
  • Public
  • Public/Protected
  • All
Menu

@jonahsnider/util

Index

Namespaces

Enumerations Cards

Classes Map

Classes Other

Interfaces Cards

Interfaces Typed EventEmitter

Type Aliases Array

Type Aliases Enum

Type Aliases Object

Type Aliases Other

Type Aliases Promise

Type Aliases Sort

Type Aliases Typed EventEmitter

Functions Array

Functions Cards

Functions Enum

Functions Format

Functions Higher order

Functions Iterable

Functions Map

Functions Math

Functions Object

Functions Other

Functions Promise

Functions Reducers

Functions Regular expressions

Functions Set

Functions Sort

Functions String

Array Type Aliases

NonEmptyArray<T>: [T, ...T[]]

An array with at least 1 element.

Type Parameters

  • T

Table<T>: T[][]

A 2-dimensional table of type T.

Type Parameters

  • T

_ArrangedLargestToSmallest<A, B>: [largest: A, smallest: B] | [largest: B, smallest: A]

A tuple of two elements arranged so the largest element is first and the smallest is last.

internal

Type Parameters

  • A

  • B

_ObjectWithLength: { length: number }

An object with a length property.

internal

Type declaration

  • length: number
_ObjectWithSize: { size: number }

An object with a size property.

internal

Type declaration

  • size: number

Enum Type Aliases

Enum<T>: Readonly<Record<string | number, T>>

A type for an enum.

Type Parameters

EnumValue: number | string

A type for an enum value.

Object Type Aliases

_NonUnion<T, U>: (T extends T ? U extends T ? false : true : never) extends false ? T : never
returns

T if T is not a union type, never otherwise.

internal

Type Parameters

  • T

  • U extends T = T

Other Type Aliases

AnyFunction<P, R>: ((...args: P) => R)

Type Parameters

  • P extends any[] = any[]

    Parameters type

  • R = any

    Return type

Type declaration

    • (...args: P): R
DirectionFn<T>: ((element: T) => number)

Type Parameters

  • T

Type declaration

    • (element: T): number
    • A function used to determine the direction a search algorithm should take when traversing data to find a desired element.

      example
      function directionFn(value: number) {
      const squared = value ** 2;

      return squared - 64;
      }

      Parameters

      • element: T

      Returns number

      0 when the desired element has been found. A positive number when the desired element appears after the current element. A negative number when the desired element appears before the current element.

Nullish: null | undefined

null or undefined.

NumberLike: { [toPrimitive]: any } | number | bigint | Number | boolean | `${number | bigint}` | `${_Sign | ""}${"Infinity"}` | null

A value that can be converted to a Number.

see

https://262.ecma-international.org/12.0/#sec-tonumber-applied-to-the-string-type ECMAScript definition of this behavior

Percentage: 0 | 0.01 | 0.02 | 0.03 | 0.04 | 0.05 | 0.06 | 0.07 | 0.08 | 0.09 | 0.1 | 0.11 | 0.12 | 0.13 | 0.14 | 0.15 | 0.16 | 0.17 | 0.18 | 0.19 | 0.2 | 0.21 | 0.22 | 0.23 | 0.24 | 0.25 | 0.26 | 0.27 | 0.28 | 0.29 | 0.3 | 0.31 | 0.32 | 0.33 | 0.34 | 0.35 | 0.36 | 0.37 | 0.38 | 0.39 | 0.4 | 0.41 | 0.42 | 0.43 | 0.44 | 0.45 | 0.46 | 0.47 | 0.48 | 0.49 | 0.5 | 0.51 | 0.52 | 0.53 | 0.54 | 0.55 | 0.56 | 0.57 | 0.58 | 0.59 | 0.6 | 0.61 | 0.62 | 0.63 | 0.64 | 0.65 | 0.66 | 0.67 | 0.68 | 0.69 | 0.7 | 0.71 | 0.72 | 0.73 | 0.74 | 0.75 | 0.76 | 0.77 | 0.78 | 0.79 | 0.8 | 0.81 | 0.82 | 0.83 | 0.84 | 0.85 | 0.86 | 0.87 | 0.88 | 0.89 | 0.9 | 0.91 | 0.92 | 0.93 | 0.94 | 0.95 | 0.96 | 0.97 | 0.98 | 0.99 | 1

A percentage within [0, 1] accurate to 2 decimal places.

UnknownFunction: ((...args: unknown[]) => unknown)

Type declaration

    • (...args: unknown[]): unknown
    • An unknown function.

      see

      AnyFunction

      Parameters

      • Rest ...args: unknown[]

      Returns unknown

_Sign: "-" | "+"

A number sign.

internal

Promise Type Aliases

RejectedResult<T>: [value: undefined, error: T]

A result type for a Promise that rejected.

Type Parameters

  • T

ResolvedResult<T>: [value: T, error: undefined]

A result type for a Promise that resolved.

Type Parameters

  • T

Result<T, E>: ResolvedResult<T> | RejectedResult<E>

A result type to represent a resolved or rejected Promise.

Type Parameters

  • T

  • E

Sort Type Aliases

Comparable: string | NumberLike

A value that can be compared numerically using <, >, <=, or >=.

CompareFn<T>: Exclude<Parameters<T[]["sort"]>[0], undefined>

Type Parameters

Typed EventEmitter Type Aliases

EventListeners: Record<Parameters<EventEmitter["on"]>[0], Parameters<EventEmitter["on"]>[1]>

An object where keys are the names of events and values are the type signature of the listener function.

example
interface SafeEvents extends EventListeners {
start: () => void;
finish: (error: Error) => void;
}

Array Functions

  • binarySearch<T>(array: ArrayLike<T>, directionFn: DirectionFn<T>): ReturnType<T[]["find"]>
  • Perform a binary search to find an element in a sorted array.

    Time complexity: O(log n)

    Space complexity: O(1)

    example
    const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    function directionFn(value: number) {
    const squared = value ** 2;

    if (squared === 64) {
    return 0;
    }

    return squared - 64;
    }

    binarySearch(array, directionFn);

    Type Parameters

    • T

    Parameters

    • array: ArrayLike<T>

      Sorted array to perform binary search on

    • directionFn: DirectionFn<T>

      The function used to determine what direction to continue searching

    Returns ReturnType<T[]["find"]>

    The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

  • chunk<T>(array: readonly T[], size: number): Table<T>
  • Divides an array into several chunks of size. If size is equal to the length of the array each item will be in their own array.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    chunk([1, 2, 3, 4, 5, 6], 2); // [[1, 2], [3, 4], [5, 6]]
    
    example
    chunk([1, 2, 3, 4, 5, 6], 5); // [[1, 2, 3, 4, 5], [6]]
    
    example
    chunk([1, 2, 3, 4, 5, 6], 6); // [[1], [2], [3], [4], [5], [6]]
    
    example
    chunk([1, 2, 3, 4, 5, 6], 100); // [[1, 2, 3, 4, 5, 6]]
    

    Type Parameters

    • T

    Parameters

    • array: readonly T[]

      The array to chunk

    • size: number

      The size of each chunk

    Returns Table<T>

    The new array containing chunks of the original array

  • fill<T>(value: T, length: number): T[]
  • Create a new array of a specified length and fill it with a given value.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    fill('a', 3); // ['a', 'a', 'a']
    
    see

    mapFill to do the same thing but with a function that generates values

    see

    repeat to do the same thing but return an iterable

    Type Parameters

    • T

    Parameters

    • value: T

      Value to fill the array with

    • length: number

      The length of the array

    Returns T[]

    The filled array

  • findIndexAll<T>(array: ArrayLike<T>, predicate: ((element: T, index: number) => boolean)): number[]
  • Get an array of all indexes of elements in an array that passed a given predicate.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    findIndexAll([1, 2, 1, 3, 1], (element) => element === 1); // [0, 2, 4]
    
    see

    indexOfAll if you want to find all elements equal to a given value

    Type Parameters

    • T

    Parameters

    • array: ArrayLike<T>

      The array to search in

    • predicate: ((element: T, index: number) => boolean)

      The function to call for each element to decide whether it should be included in the result

        • (element: T, index: number): boolean
        • Parameters

          • element: T
          • index: number

          Returns boolean

    Returns number[]

    An array of indexes of elements that passed predicate in array

  • firstIndexOfLastGroup<T>(array: ArrayLike<T>, value: T): number
  • Returns the first index of the last continuous group of a given value. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const array = ['a', 'a', 'b', 'b', 'c', 'c'];

    firstIndexOfLastGroup(array, 'c'); // 4
    see

    lastIndexOfFirstGroup to do the same thing but find the last index of the first group

    Type Parameters

    • T

    Parameters

    • array: ArrayLike<T>

      The array to search

    • value: T

      The value to search for

    Returns number

    The first index of the last group of a given value

  • holes(array: ArrayLike<unknown>): number[]
  • Get an array of indexes of holes in an array.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    holes([0, , 2]); // [1]
    

    Parameters

    • array: ArrayLike<unknown>

      The array to find holes in

    Returns number[]

    An array of indexes of holes in the array

  • indexOfAll<T>(array: ArrayLike<T>, searchElement: T): number[]
  • Get an array of indexes of searchElement in an array. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    indexOfAll([1, 2, 1, 3, 1], 1); // [0, 2, 4]
    
    see

    findIndexAll if you want to use a predicate instead of strict equality

    Type Parameters

    • T

    Parameters

    • array: ArrayLike<T>

      The array to search in

    • searchElement: T

      The element to search for

    Returns number[]

    An array of indexes of searchElement in array

  • isEmpty(map: ReadonlyMap<unknown, unknown>): map is ReadonlyMap<never, never>
  • isEmpty(map: Map<unknown, unknown>): map is Map<never, never>
  • isEmpty(set: ReadonlySet<unknown>): set is ReadonlySet<never>
  • isEmpty(set: Set<unknown>): set is Set<never>
  • isEmpty(string: string): string is ""
  • isEmpty(array: readonly unknown[]): array is readonly []
  • isEmpty(array: unknown[]): array is []
  • isEmpty(iterable: Iterable<unknown>): iterable is Iterable<never>
  • Check if a readonly Map is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Map([1, 2, 3])); // false
    
    example
    isEmpty(new Map()); // true
    

    Parameters

    • map: ReadonlyMap<unknown, unknown>

      The Map to check

    Returns map is ReadonlyMap<never, never>

    true if map is empty, false otherwise

  • Check if a Map is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Map([['a', 1], ['b', 2], ['c', 3]])); // false
    
    example
    isEmpty(new Map()); // true
    

    Parameters

    • map: Map<unknown, unknown>

      The Map to check

    Returns map is Map<never, never>

    true if map is empty, false otherwise

  • Check if a readonly Set is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Set([1, 2, 3])); // false
    
    example
    isEmpty(new Set()); // true
    

    Parameters

    • set: ReadonlySet<unknown>

      The Set to check

    Returns set is ReadonlySet<never>

    true if set is empty, false otherwise

  • Check if a Set is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Set([1, 2, 3])); // false
    
    example
    isEmpty(new Set()); // true
    

    Parameters

    • set: Set<unknown>

      The Set to check

    Returns set is Set<never>

    true if set is empty, false otherwise

  • Check if a string is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty('hello'); // false
    
    example
    isEmpty(''); // true
    

    Parameters

    • string: string

      The string to check

    Returns string is ""

    true if string is empty, false otherwise

  • Check if a readonly array is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • array: readonly unknown[]

      The array to check

    Returns array is readonly []

    true if array is empty, false otherwise

  • Check if an array is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • array: unknown[]

      The array to check

    Returns array is []

    true if array is empty, false otherwise

  • Check if an iterable is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • iterable: Iterable<unknown>

      The iterable to check

    Returns iterable is Iterable<never>

    true if iterable is empty, false otherwise

  • Arrange 2 objects in a tuple by their length. Useful for situations where you are iterating a or b depending on which is larger.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const a = [1, 2];
    const b = [1, 2, 3];

    const [largest, smallest] = largeToSmall(a, b);

    console.log(largest); // [1, 2, 3]
    console.log(smallest); // [1, 2]
    throws

    If a does not have a length or size property

    Type Parameters

    Parameters

    • a: A

      First object

    • b: B

      Second object

    Returns _ArrangedLargestToSmallest<A, B>

  • Arrange 2 objects in a tuple by their size. Useful for situations where you are iterating a or b depending on which is larger.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const a = new Set([1, 2]);
    const b = new Set([1, 2, 3]);

    const [largest, smallest] = largeToSmall(a, b);

    console.log(largest); // Set(3) { 1, 2, 3 }
    console.log(smallest); // Set(2) { 1, 2 }
    throws

    If a does not have a length or size property

    Type Parameters

    Parameters

    • a: A

      First object

    • b: B

      Second object

    Returns _ArrangedLargestToSmallest<A, B>

  • mapFill<T>(valueFn: ((index: number) => T), length: number): T[]
  • Create a new array of a specified length and fill it using the given function.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    mapFill(i => i + 1, 3); // [1, 2, 3]
    
    see

    mapRepeat to do the same thing but return an iterable

    see

    fill to do the same thing but with a given value

    Type Parameters

    • T

    Parameters

    • valueFn: ((index: number) => T)

      A function that returns each value to fill the array with

        • (index: number): T
        • Parameters

          • index: number

          Returns T

    • length: number

      The length of the array

    Returns T[]

    The filled array

  • overwrite<T>(array: T[], startIndex: number, data: ArrayLike<T> & Iterable<T>): ReturnType<typeof array["splice"]>
  • Overwrite elements in an array at a given index.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const array = [1, 2, 3, 4, 5];

    overwrite(array, 1, [8, 9]); // [2, 3]

    console.log(array); // [1, 8, 9, 4, 5]

    Type Parameters

    • T

    Parameters

    • array: T[]

      The array to overwrite elements in

    • startIndex: number

      The index to start overwriting elements from

    • data: ArrayLike<T> & Iterable<T>

    Returns ReturnType<typeof array["splice"]>

    The return value of Array.prototype.splice

  • padEnd<T>(array: T[], maxLength: number, fillValue: T): void
  • Pads an array with a given value so that the array reaches a given length. The padding is applied from the end (right) of the array.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const array = [0, 1, 2];

    padEnd(array, 4, 4);

    console.log(array); // [0, 1, 2, 4]
    see

    padStart to pad the start of an array

    Type Parameters

    • T

    Parameters

    • array: T[]

      The array to pad

    • maxLength: number

      The length of array once it has been padded. If this parameter is smaller than array's length, array will not be modified

    • fillValue: T

      The value to pad the array with

    Returns void

  • padStart<T>(array: T[], maxLength: number, fillValue: T): void
  • Pads an array with a given value so that the array reaches a given length. The padding is applied from the start (left) of the array.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const array = [1, 2, 3];

    padStart(array, 4, 0);

    console.log(array); // [0, 1, 2, 3]
    see

    padEnd to pad the end of an array

    Type Parameters

    • T

    Parameters

    • array: T[]

      The array to pad

    • maxLength: number

      The length of array once it has been padded. If this parameter is smaller than the current string's length, array will not be modified

    • fillValue: T

      The value to pad the array with

    Returns void

  • pull<T>(array: T[], element: T): ReturnType<typeof array["splice"]>
  • Remove an element from an array.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const array = [1, 2, 3];

    pull(array, 2); // [2]
    console.log(array); // [1, 3]

    pull(array, 2); // []
    console.log(array); // [1, 3]

    Type Parameters

    • T

    Parameters

    • array: T[]

      The array to remove an element from

    • element: T

      The element to remove

    Returns ReturnType<typeof array["splice"]>

    The return value of Array.prototype.splice

  • pullAll<T>(array: T[], element: T): ReturnType<typeof array["splice"]>
  • Remove all elements equal to a given element from an array. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const array = [1, 1, 2, 2, 3, 3];

    pullAll(array, 2); // [2, 2]
    console.log(array); // [1, 1, 3, 3]

    pullAll(array, 2); // []
    console.log(array); // [1, 1, 3, 3]

    Type Parameters

    • T

    Parameters

    • array: T[]

      The array to remove elements from

    • element: T

      The element to remove

    Returns ReturnType<typeof array["splice"]>

    The return value of Array.prototype.splice

  • replace<T>(array: T[], searchElement: T, replacement: T): number
  • Replace the first occurrence of searchElement with replacement in an array. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const array = [1, 2, 1, 3, 1];

    replace(array, 1, 2);

    console.log(array); // [2, 2, 1, 3, 1]

    Type Parameters

    • T

    Parameters

    • array: T[]

      The array to replace elements in

    • searchElement: T

      The element to search for

    • replacement: T

      The element to replace searchElement with

    Returns number

    The index of the replaced element, or -1 if it is not present.

  • replaceAll<T>(array: T[], searchElement: T, replacement: T): number
  • Replace all occurrences of searchElement with replacement in an array. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const array = [1, 2, 1, 3, 1];

    replaceAll(array, 1, 2);

    console.log(array); // [2, 2, 2, 3, 2]

    Type Parameters

    • T

    Parameters

    • array: T[]

      The array to replace elements in

    • searchElement: T

      The element to search for

    • replacement: T

      The element to replace searchElement with

    Returns number

    The number of elements replaced

  • sample<T>(array: ArrayLike<T>): T | undefined
  • Samples a single element at random from an array.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const array = [1, 2, 3];

    sample(array); // 1, 2, or 3
    see

    {@link (shuffle:1)} if you want to implement a random selection without replacement

    Type Parameters

    • T

    Parameters

    • array: ArrayLike<T>

      Array to sample element from

    Returns T | undefined

    A random element from the array or undefined if the array was empty

  • shuffle<T>(array: T[], mutate?: true): void
  • shuffle<T>(array: ArrayLike<T> & Iterable<T>, mutate: false): T[]
  • A mutating (in-place) uniformly random array shuffle.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const array = [1, 2, 3];

    shuffle(array);
    see

    sample if you only want to select one element at random

    Type Parameters

    • T

    Parameters

    • array: T[]

      Array to shuffle

    • Optional mutate: true

      Optional, true if specified

    Returns void

  • A non-mutating uniformly random array shuffle.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const array = [1, 2, 3];

    const shuffled = shuffle(array, false);
    see

    sample if you only want to select one element at random

    Type Parameters

    • T

    Parameters

    • array: ArrayLike<T> & Iterable<T>

      Array to shuffle

    • mutate: false

      false

    Returns T[]

    The shuffled array

  • trimEnd(string: string, end: string): string
  • trimEnd<T>(array: readonly T[], end: T): T[]
  • Removes the trailing end characters from a string.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    trimEnd('aabbcc', 'c'); // 'aabb'
    
    see

    {@link (trimStart:1)} to do the same thing but trim from the start of a string

    Parameters

    • string: string

      The string to trim

    • end: string

      The character to remove from the end of string

    Returns string

    A string with the leading end characters removed

  • Removes the trailing end characters from an array.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    trimEnd(['a', 'a', 'b', 'b', 'c', 'c'], 'c'); // ['a', 'a', 'b', 'b']
    
    see

    {@link (trimStart:2)} to do the same thing but trim from the start of an array

    Type Parameters

    • T

    Parameters

    • array: readonly T[]

      The array to trim

    • end: T

      The character to remove from the end of array

    Returns T[]

    A shallow-copied array with the trailing start characters removed

  • trimStart(string: string, start: string): string
  • trimStart<T>(array: readonly T[], start: T): T[]
  • Removes the leading start characters from a string.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    trimStart('aabbcc', 'a'); // 'bbcc'
    
    see

    {@link (trimEnd:1)} to do the same thing but trim from the end of a string

    Parameters

    • string: string

      The string to trim

    • start: string

      The character to remove from the start of string

    Returns string

    A string with the leading start characters removed

  • Removes the leading start characters from an array.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    trimStart(['a', 'a', 'b', 'b', 'c', 'c'], 'a'); // ['b', 'b', 'c', 'c']
    
    see

    {@link (trimEnd:2)} to do the same thing but trim from the end of an array

    Type Parameters

    • T

    Parameters

    • array: readonly T[]

      The array to trim

    • start: T

      The character to remove from the start of array

    Returns T[]

    A shallow-copied array with the leading start characters removed

Cards Functions

  • Get a sorted deck of cards.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    import { shuffle } from '@jonahsnider/util';

    const deck = newDeck();

    Returns Card[]

    A sorted deck of cards

Enum Functions

  • enumHas<T>(Enum: Readonly<Record<string | number, T>>, value: unknown): value is T
  • Check whether a given value is a member value of an enum.

    Time complexity: O(1) if Enum has been seen before. Otherwise, O(n) where n is the number of enum values.

    Space complexity: O(1) if Enum has been seen before. Otherwise, O(n) where n is the number of unique enum values.

    example
    enum Enum {
    A,
    B,
    }

    enumHas(Enum, 0); // true
    enumHas(Enum, 2); // false

    Type Parameters

    Parameters

    • Enum: Readonly<Record<string | number, T>>

      The enum to use as the source of member values

    • value: unknown

      The value to check

    Returns value is T

    Whether value is a member value of Enum

Format Functions

  • formatTable(table: Table<string>, delimiter?: string): string
  • Format a table into a string of equally sized columns.

    Time complexity: O(n) where n is the number of rows * columns.

    Space complexity: O(n)

    Parameters

    • table: Table<string>

      Table to format

    • delimiter: string = ' '

      Delimiter to use in columns

    Returns string

    A formatted string representation of the table

  • maxColumnLength(table: Table<string>): number[]
  • Get the lengths of each column in a table. Can include a header.

    Time complexity: O(n) where n is the number of rows * columns.

    Space complexity: O(n)

    Parameters

    • table: Table<string>

      The table of strings to use for calculations

    Returns number[]

    An array of lengths

Higher order Functions

  • invert<T>(fn: T): T
  • Create a new function taht calls the provided fn and then inverts the sign of the result.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    function sort(a, b) {
    return a - b;
    }

    const inverted = invert(sort);

    inverted(10, 5); // -5

    Type Parameters

    Parameters

    • fn: T

      Function to invert return value of

    Returns T

    The inverted return value of fn

  • not<T>(fn: T): ((...parameters: Parameters<T>) => boolean)
  • Create a new function that calls the provided fn and negates the result.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    import { nullish } from '@jonahsnider/util';

    const array = [0, null, '', undefined, false];

    array.filter(not(nullish)); // [0, '', false]

    Type Parameters

    • T extends ((...parameters: any[]) => boolean)

    Parameters

    • fn: T

      Function to negate the return value of

    Returns ((...parameters: Parameters<T>) => boolean)

    The inverted return value of fn

      • (...parameters: Parameters<T>): boolean
      • Create a new function that calls the provided fn and negates the result.

        Time complexity: O(1)

        Space complexity: O(1)

        example
        import { nullish } from '@jonahsnider/util';

        const array = [0, null, '', undefined, false];

        array.filter(not(nullish)); // [0, '', false]
        category

        Higher order

        Parameters

        • Rest ...parameters: Parameters<T>

        Returns boolean

        The inverted return value of fn

  • thunkify<T>(fn: T): ((...parameters: Parameters<T>) => ReturnType<T>)
  • Create a new function that calls the provided fn with the given arguments. After the first call the return value will be cached and returned again, meaning you technically only need to pass the arguments the first time.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    function add(a, b) {
    return a + b;
    }

    const thunk = thunkify(add);

    thunk(1, 2); // 3
    thunk(3, 4); // 3

    Type Parameters

    • T extends ((...args: unknown[]) => unknown)

    Parameters

    • fn: T

      The function to thunkify

    Returns ((...parameters: Parameters<T>) => ReturnType<T>)

    A function that returns whatever the first call of fn returns for the given arguments

      • (...parameters: Parameters<T>): ReturnType<T>
      • Create a new function that calls the provided fn with the given arguments. After the first call the return value will be cached and returned again, meaning you technically only need to pass the arguments the first time.

        Time complexity: O(1)

        Space complexity: O(1)

        example
        function add(a, b) {
        return a + b;
        }

        const thunk = thunkify(add);

        thunk(1, 2); // 3
        thunk(3, 4); // 3
        category

        Higher order

        Parameters

        • Rest ...parameters: Parameters<T>

        Returns ReturnType<T>

        A function that returns whatever the first call of fn returns for the given arguments

Iterable Functions

  • allDuplicates<T>(iterable: Iterable<T>): T[]
  • Get an array of all the duplicate elements in an iterable.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    allDuplicates([1, 2, 2, 2, 3]); // [2, 2]
    
    example

    Using frequencyTable to get the number of times each element was duplicated

    frequencyTable(allDuplicates([1, 2, 2, 2, 3, 3])); // Map(2) { 2 => 2, 3 => 1 }
    
    see

    duplicates to receive a Set of duplicate elements instead of an array (which can include the same element more than once)

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to find duplicates in

    Returns T[]

    An array of the duplicated elements

  • combineIterables<T>(...iterables: readonly Iterable<T>[]): Iterable<T>
  • Combines multiple iterables into a single iterable.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    [...combineIterables([1, 2, 3], [4, 5, 6])]; // [1, 2, 3, 4, 5, 6]
    

    Type Parameters

    • T

    Parameters

    • Rest ...iterables: readonly Iterable<T>[]

      The iterables to combine

    Returns Iterable<T>

    A single iterable containing all the elements of all the iterables

  • count<T>(iterable: Iterable<T>, filterPredicate?: ((element: T) => boolean)): number
  • Count the number of elements in an iterable You may optionally provide a predicate function to filter which elements are counted.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    count([1, 2, 3]); // 3
    
    example
    count([1, 2, 3], number => number % 2 === 1); // 2
    
    see

    frequencyTable to count the occurrences of all elements in an iterable

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to count the elements of

    • Optional filterPredicate: ((element: T) => boolean)
        • (element: T): boolean
        • Parameters

          • element: T

          Returns boolean

    Returns number

    The number of elements in iterable. If predicate was provided, the number of elements in iterable that satisfy predicate.

  • cycle<T>(iterable: Iterable<T>, times: number): Iterable<T>
  • Returns an array with the elements of the iterable repeated a provided number of times.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    [...cycle(['a', 'b'], 2)]; // ['a', 'b', 'a', 'b']
    

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to cycle

    • times: number

      The number of times to repeat the elements of iterable

    Returns Iterable<T>

    An array with the elements of iterable repeated times number of times

  • duplicates<T>(iterable: Iterable<T>): Set<T>
  • Get a Set of the duplicate elements in an iterable.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    duplicates([1, 2, 2, 2, 3]); // Set(1) { 2 }
    
    see

    allDuplicates to receive a array of duplicate elements instead of a Set (which doesn't include the same element more than once)

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to find duplicates in

    Returns Set<T>

    A Set of the duplicated elements

  • every<T, S>(iterable: Iterable<T>, predicate: ((element: T) => element is S)): iterable is Iterable<S>
  • every<T>(iterable: Iterable<T>, predicate: ((element: T) => unknown)): boolean
  • Determines whether all the elements of an iterable pass a given predicate.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    every([false], x => x); // false
    
    example
    every([false, true], x => x); // false
    
    example
    every([true], x => x); // true
    

    Type Parameters

    • T

    • S

    Parameters

    • iterable: Iterable<T>

      The iterable to take elements from

    • predicate: ((element: T) => element is S)

      The function to call on each element in the iterable to determine if it passes the test

        • (element: T): element is S
        • Parameters

          • element: T

          Returns element is S

    Returns iterable is Iterable<S>

    true if every element passed the predicate, false otherwise

  • Determines whether all the elements of an iterable pass a given predicate.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    every([false], x => x); // false
    
    example
    every([false, true], x => x); // false
    
    example
    every([true], x => x); // true
    

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to take elements from

    • predicate: ((element: T) => unknown)

      The function to call on each element in the iterable to determine if it passes the test

        • (element: T): unknown
        • Parameters

          • element: T

          Returns unknown

    Returns boolean

    true if every element passed the predicate, false otherwise

  • find<T>(iterable: Iterable<T>, predicate: ((element: T) => boolean)): T | undefined
  • Returns the value of the first element in the iterable where predicate is truthy, and undefined otherwise.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    find([1, 2, 3], x => x === 2); // 2
    

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to take elements from

    • predicate: ((element: T) => boolean)

      The function to call on each element in the iterable to determine if it passes the test

        • (element: T): boolean
        • Parameters

          • element: T

          Returns boolean

    Returns T | undefined

    The value of the first element in the iterable where predicate is truthy, and undefined otherwise

  • first<T>(iterable: Iterable<T>, take?: undefined): T | undefined
  • first<T>(iterable: Iterable<T>, take: number): Iterable<T>
  • Get the first element from an iterable.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    first([1, 2, 3]); // 1
    

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to take elements from

    • Optional take: undefined

    Returns T | undefined

    The first element of the iterable

  • Get the first n elements from an iterable.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    [...first([1, 2, 3], 1)]; // [1]
    
    example
    [...first([1, 2, 3], 2)]; // [1, 2]
    

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to take elements from

    • take: number

      The number of elements to take from the iterable

    Returns Iterable<T>

    The first take elements of the iterable

  • frequencyTable<T>(iterable: Iterable<T>): Map<T, number>
  • Construct a frequency table from an iterable. Similar to Python's Counter class.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    frequencyTable([1, 2, 2, 3, 3, 3]) // Map(3) { 1 => 1, 2 => 2, 3 => 3 };
    
    see

    count to count the occurrences of one value in an iterable

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to construct a frequency table for

    Returns Map<T, number>

    A frequency table represented as a Map where keys are the elements and values are the frequency

  • includes<T>(iterable: Iterable<T>, searchElement: T): boolean
  • Determines whether an iterable includes a certain element, returning true or false as appropriate. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    includes([1, 2, 3], 2); // true
    
    example
    includes([1, 2, 3], 4); // false
    

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to take elements from

    • searchElement: T

      The element to search for

    Returns boolean

    true if any element is truthy, false otherwise

  • isEmpty(map: ReadonlyMap<unknown, unknown>): map is ReadonlyMap<never, never>
  • isEmpty(map: Map<unknown, unknown>): map is Map<never, never>
  • isEmpty(set: ReadonlySet<unknown>): set is ReadonlySet<never>
  • isEmpty(set: Set<unknown>): set is Set<never>
  • isEmpty(string: string): string is ""
  • isEmpty(array: readonly unknown[]): array is readonly []
  • isEmpty(array: unknown[]): array is []
  • isEmpty(iterable: Iterable<unknown>): iterable is Iterable<never>
  • Check if a readonly Map is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Map([1, 2, 3])); // false
    
    example
    isEmpty(new Map()); // true
    

    Parameters

    • map: ReadonlyMap<unknown, unknown>

      The Map to check

    Returns map is ReadonlyMap<never, never>

    true if map is empty, false otherwise

  • Check if a Map is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Map([['a', 1], ['b', 2], ['c', 3]])); // false
    
    example
    isEmpty(new Map()); // true
    

    Parameters

    • map: Map<unknown, unknown>

      The Map to check

    Returns map is Map<never, never>

    true if map is empty, false otherwise

  • Check if a readonly Set is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Set([1, 2, 3])); // false
    
    example
    isEmpty(new Set()); // true
    

    Parameters

    • set: ReadonlySet<unknown>

      The Set to check

    Returns set is ReadonlySet<never>

    true if set is empty, false otherwise

  • Check if a Set is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Set([1, 2, 3])); // false
    
    example
    isEmpty(new Set()); // true
    

    Parameters

    • set: Set<unknown>

      The Set to check

    Returns set is Set<never>

    true if set is empty, false otherwise

  • Check if a string is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty('hello'); // false
    
    example
    isEmpty(''); // true
    

    Parameters

    • string: string

      The string to check

    Returns string is ""

    true if string is empty, false otherwise

  • Check if a readonly array is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • array: readonly unknown[]

      The array to check

    Returns array is readonly []

    true if array is empty, false otherwise

  • Check if an array is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • array: unknown[]

      The array to check

    Returns array is []

    true if array is empty, false otherwise

  • Check if an iterable is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • iterable: Iterable<unknown>

      The iterable to check

    Returns iterable is Iterable<never>

    true if iterable is empty, false otherwise

  • iteratorToIterable<T>(iterator: Iterator<T, any, undefined>): Iterable<T>
  • Returns an iterable that uses a provided iterator.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const iterable = [1, 2, 3];
    const iterator = iterable[Symbol.iterator]();

    iteratorToIterable(iterator); // { [Symbol.iterator]: () => iterator }

    Type Parameters

    • T

    Parameters

    • iterator: Iterator<T, any, undefined>

      The iterator to convert to an iterable

    Returns Iterable<T>

    An iterable that uses iterator

  • join(iterable: Iterable<unknown>, separator?: string): string
  • Adds all the elements of an iterable into a string, separated by the specified separator string.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    join(['a', 'b', 'c']); // 'a,b,c'
    
    example
    join(['a', 'b', 'c'], '-'); // 'a-b-c'
    

    Parameters

    • iterable: Iterable<unknown>

      The iterable to join

    • separator: string = ','

      A string used to separate one element of the iterable from the next in the resulting string

    Returns string

    A string containing the elements in iterable joined by separator

  • lastIndexOfFirstGroup<T>(iterable: Iterable<T>, value: T): number
  • Returns the last index of the first continuous group of a given value. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const iterable = ['a', 'a', 'b', 'b', 'c', 'c'];

    lastIndexOfFirstGroup(iterable, 'a'); // 1
    see

    firstIndexOfLastGroup to do the same thing but find the first index of the last group

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to search

    • value: T

      The value to search for

    Returns number

    The last index of the first group of a given value

  • mapRepeat<T>(valueFn: ((increment: number) => T), times: number): Iterable<T>
  • Returns an iterable that uses a function that generates values a given number of times.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    [...mapRepeat((increment) => increment ** 2, 5)]; // [0, 1, 4, 9, 16]
    
    see

    mapFill to do the same thing but return an array

    see

    repeat to do the same thing but with a given value

    Type Parameters

    • T

    Parameters

    • valueFn: ((increment: number) => T)

      A function that returns each value to fill the array with

        • (increment: number): T
        • Parameters

          • increment: number

          Returns T

    • times: number

      The number of times to repeat the value

    Returns Iterable<T>

    An iterable that repeats value times number of times

  • partition<S, T>(iterable: Iterable<T>, typeGuard: ((element: T) => element is S)): [passed: S[], failed: Exclude<T, S>[]]
  • partition<T>(iterable: Iterable<T>, predicate: ((value: T, increment: number) => unknown)): [passed: T[], failed: T[]]
  • Split an iterable into 2 arrays of elements that passed or failed a provided type guard.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const [numbers, strings] = partition(['a', 1, 'b', 2, 'c', 3], (element): element is number => typeof element === 'number');

    console.log(numbers); // [1, 2, 3]
    console.log(strings); // ['a', 'b', 'c']

    Type Parameters

    • S

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to partition

    • typeGuard: ((element: T) => element is S)

      The type guard to apply to each element of iterable. If the type guard returns a truthy value the element will be added to the passed array in the result. Otherwise, it will be added to the failed array.

        • (element: T): element is S
        • Parameters

          • element: T

          Returns element is S

    Returns [passed: S[], failed: Exclude<T, S>[]]

    A tuple where the 1st element is an array of elements that passed the predicate (passed) and the 2nd element are the elements that failed the predicate (failed)

  • Split an iterable into 2 arrays of elements that passed or failed a provided predicate.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const [odd, even] = partition([1, 2, 3, 4, 5, 6], num => num % 2);

    console.log(odd); // [1, 3, 5]
    console.log(even); // [2, 4, 6]

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to partition

    • predicate: ((value: T, increment: number) => unknown)

      The predicate to apply to each element of iterable. If the predicate returns a truthy value the element will be added to the passed array in the result. Otherwise, it will be added to the failed array.

        • (value: T, increment: number): unknown
        • Parameters

          • value: T
          • increment: number

          Returns unknown

    Returns [passed: T[], failed: T[]]

    A tuple where the 1st element is an array of elements that passed the predicate (passed) and the 2nd element are the elements that failed the predicate (failed)

  • repeat<T>(value: T, times: number): Iterable<T>
  • Returns an iterable that repeats a given value a given number of times.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    [...repeat('a', 3)]; // ['a', 'a', 'a']
    
    see

    fill to do the same thing but return an array

    see

    mapRepeat to do the same thing but with a function that generates values

    Type Parameters

    • T

    Parameters

    • value: T

      The value to repeat

    • times: number

      The number of times to repeat the value

    Returns Iterable<T>

    An iterable that repeats value times number of times

  • skip<T>(iterable: Iterable<T>, count: number): Iterator<T>
  • Returns an iterator that skips the first count elements of an iterable.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const iterable = [1, 2, 3, 4, 5];

    const iterator = skip(iterable, 2);

    iterator.next(); // { value: 3, done: false }

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to skip elements from

    • count: number

      The number of elements to skip

    Returns Iterator<T>

    The iterator that skips the first count elements of iterable

  • some<T>(iterable: Iterable<T>, predicate: ((element: T) => unknown)): boolean
  • Determines whether any of the elements of an iterable pass a given predicate.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    some([false], x => x); // false
    
    example
    some([false, true], x => x); // true
    
    example
    some([true], x => x); // true
    

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to take elements from

    • predicate: ((element: T) => unknown)

      The function to call on each element in the iterable to determine if it passes the test

        • (element: T): unknown
        • Parameters

          • element: T

          Returns unknown

    Returns boolean

    true if any element passes the predicate, false otherwise

Map Functions

  • isEmpty(map: ReadonlyMap<unknown, unknown>): map is ReadonlyMap<never, never>
  • isEmpty(map: Map<unknown, unknown>): map is Map<never, never>
  • isEmpty(set: ReadonlySet<unknown>): set is ReadonlySet<never>
  • isEmpty(set: Set<unknown>): set is Set<never>
  • isEmpty(string: string): string is ""
  • isEmpty(array: readonly unknown[]): array is readonly []
  • isEmpty(array: unknown[]): array is []
  • isEmpty(iterable: Iterable<unknown>): iterable is Iterable<never>
  • Check if a readonly Map is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Map([1, 2, 3])); // false
    
    example
    isEmpty(new Map()); // true
    

    Parameters

    • map: ReadonlyMap<unknown, unknown>

      The Map to check

    Returns map is ReadonlyMap<never, never>

    true if map is empty, false otherwise

  • Check if a Map is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Map([['a', 1], ['b', 2], ['c', 3]])); // false
    
    example
    isEmpty(new Map()); // true
    

    Parameters

    • map: Map<unknown, unknown>

      The Map to check

    Returns map is Map<never, never>

    true if map is empty, false otherwise

  • Check if a readonly Set is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Set([1, 2, 3])); // false
    
    example
    isEmpty(new Set()); // true
    

    Parameters

    • set: ReadonlySet<unknown>

      The Set to check

    Returns set is ReadonlySet<never>

    true if set is empty, false otherwise

  • Check if a Set is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Set([1, 2, 3])); // false
    
    example
    isEmpty(new Set()); // true
    

    Parameters

    • set: Set<unknown>

      The Set to check

    Returns set is Set<never>

    true if set is empty, false otherwise

  • Check if a string is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty('hello'); // false
    
    example
    isEmpty(''); // true
    

    Parameters

    • string: string

      The string to check

    Returns string is ""

    true if string is empty, false otherwise

  • Check if a readonly array is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • array: readonly unknown[]

      The array to check

    Returns array is readonly []

    true if array is empty, false otherwise

  • Check if an array is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • array: unknown[]

      The array to check

    Returns array is []

    true if array is empty, false otherwise

  • Check if an iterable is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • iterable: Iterable<unknown>

      The iterable to check

    Returns iterable is Iterable<never>

    true if iterable is empty, false otherwise

Math Functions

  • clamp<T, M1, M2>(value: T, min: M1, max: M2): T | M1 | M2
  • Returns the value nearest to value which is within the closed range [min, max].

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const value = clamp(Math.random() * 100, 25, 75n);

    console.log(25 <= value && value <= 75n); // true

    Type Parameters

    • T extends number | bigint

    • M1 extends number | bigint

    • M2 extends number | bigint

    Parameters

    • value: T

      The value to clamp

    • min: M1

      The lower bound of the range of numbers

    • max: M2

      The upper bound of the range of numbers

    Returns T | M1 | M2

    The value nearest to value which is within the provided range

  • geometricMean(array: readonly number[]): number
  • Get the geometric mean of an array of numbers.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const array = [1, 2, 3, 4];

    geometricMean(array); // 24 ** (1 / 4)
    see

    {@link (mean:1)} to calculate the arithmetic mean of an array

    see

    geometricMean to calculate the harmonic mean of an array

    Parameters

    • array: readonly number[]

      The array to calculate the mean of

    Returns number

    The geometric mean of the array

  • harmonicMean(array: readonly number[]): number
  • Get the harmonic mean of an array of numbers.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const array = [1, 4, 4];

    harmonicMean(array); // 2
    see

    {@link (mean:1)} to calculate the arithmetic mean of an array

    see

    geometricMean to calculate the arithmetic mean of an array

    Parameters

    • array: readonly number[]

      The array to calculate the mean of

    Returns number

    The geometric mean of the array

  • mean(array: readonly number[]): number
  • mean(array: readonly bigint[]): bigint
  • Get the arithmetic mean of an array of numbers.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const array = [1, 2, 3];

    mean(array); // 2
    see

    {@link (median:1)} to calculate the median of an array

    see

    mode to calculate the mode of an array

    see

    geometricMean to calculate the geometric mean of an array

    see

    harmonicMean to calculate the harmonic mean of an array

    Parameters

    • array: readonly number[]

      The array to calculate the mean of

    Returns number

    The mean of the array

  • Get the arithmetic mean of an array of bigints.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const array = [1n, 2n, 3n];

    mean(array); // 2n
    see

    {@link (median:2)} to calculate the median of an array

    see

    mode to calculate the mode of an array

    Parameters

    • array: readonly bigint[]

      The array to calculate the mean of

    Returns bigint

    The mean of the array

  • median(array: ArrayLike<number>): number
  • median(array: ArrayLike<bigint>): bigint
  • Calculate the median of an array of numbers.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const values = [1, 2, 3];

    median(values); // 2
    see

    {@link (mean:1)} to calculate the mean of an array

    see

    mode to calculate the mode of an array

    Parameters

    • array: ArrayLike<number>

      Values to use in the calculation

    Returns number

    The median of values

  • Calculate the median of an array of bigints.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const values = [1n, 2n, 3n];

    median(values); // 2n
    see

    {@link (mean:2)} to calculate the mean of an array

    see

    mode to calculate the mode of an array

    Parameters

    • array: ArrayLike<bigint>

      Values to use in the calculation

    Returns bigint

    The median of values

  • mode<T>(iterable: Iterable<T>): T[]
  • Calculate the mode of an iterable. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const values = [1, 2, 2, 3, 3];

    mode(values); // [2, 3]
    see

    {@link (mean:1)} to calculate the mean of an array

    see

    {@link (median:1)} to calculate the median of an array

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      Values to use in the calculation

    Returns T[]

    An array of the modes of values

  • normaldist(x: number, standardDeviation: number, mean: number): number
  • Calculate the normal distribution.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    normaldist(0, 1, 0);
    
    see

    standardNormaldist For calculating the standard normal distribution

    Parameters

    • x: number

      Sample to calculate the normal distribution of

    • standardDeviation: number

      Standard deviation

    • mean: number

      Mean

    Returns number

    The normal distribution

  • random(min: number, max: number): number
  • Generate a random number within the given bounds.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const value = random(0, 10);

    0 <= value && value < 10;

    Parameters

    • min: number

      Lower bound (inclusive) of the output range

    • max: number

      Upper bound (exclusive) of the output range

    Returns number

    A random number within the given bounds

  • randomInt(min: number, max: number): number
  • Generate a random integer within the given bounds.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    randomInt(0, 3); // 0, 1, or 2
    

    Parameters

    • min: number

      Lower bound (inclusive) of the output range

    • max: number

      Upper bound (exclusive) of the output range

    Returns number

    A random integer within the given bounds

  • relativeStddev(values: readonly number[], meanValue?: number): number
  • Calculate the relative standard deviation (coefficient of variation) of a sequence of numbers.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    relativeStddev([1, 2, 3]); // 0.5
    

    Parameters

    • values: readonly number[]

      Values to use in the calculation

    • meanValue: number = ...

      The mean of values, will be calculated if not provided

    Returns number

    The standard deviation of values

  • standardNormaldist(x: number): number
  • Calculate the standard normal distribution.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    standardNormaldist(0) === normaldist(0, 1, 0); // true
    
    see

    normaldist For calculating the normal distribution

    Parameters

    • x: number

      Sample to calculate the normal distribution of

    Returns number

    The standard normal distribution

  • stddev(values: readonly number[], meanValue?: number): number
  • Calculate the standard deviation of a sequence of numbers.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    stddev([1, 2, 3]); // 1
    

    Parameters

    • values: readonly number[]

      Values to use in the calculation

    • meanValue: number = ...

      The mean of values, will be calculated if not provided

    Returns number

    The standard deviation of values

  • triangularNumber(value: number): number
  • triangularNumber(value: bigint): bigint
  • Calculate the nth triangular number for a provided number.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    triangularNumber(2); // 3
    

    Parameters

    • value: number

      The number to calculate the triangular number for

    Returns number

    The nth triangular number for the provided value

  • Calculate the nth triangular number for a provided bigint.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    triangularNumber(2n); // 3n
    

    Parameters

    • value: bigint

      The number to calculate the triangular number for

    Returns bigint

    The nth triangular number for the provided value

  • variance(values: readonly number[], meanValue?: number): number
  • Calculate the variance of a sequence of numbers.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    variance([1, 2, 3]); // 1
    

    Parameters

    • values: readonly number[]

      Values to use in the calculation

    • meanValue: number = ...

      The mean of values, will be calculated if not provided

    Returns number

    The variance of values

Object Functions

  • name(ctor: (new (...args: any[]) => any), method: AnyFunction<any[], any>): `${string}${"." | "#"}${string}`
  • name(func: AnyFunction<any[], any> | (new (...args: any[]) => any)): string
  • Get a string name for a class method.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    class Class {
    static staticMethod() {}
    }

    name(Class, Class.staticMethod); // 'Class.staticMethod'
    example
    class Class {
    instanceMethod() {}
    }

    name(Class, Class.prototype.instanceMethod); // 'Class#instanceMethod'

    Parameters

    • ctor: (new (...args: any[]) => any)

      The class to use as the first part of the name

        • new (...args: any[]): any
        • Parameters

          • Rest ...args: any[]

          Returns any

    • method: AnyFunction<any[], any>

      The method to use as the second part of the name

    Returns `${string}${"." | "#"}${string}`

    A string name for the method

  • Get the name of a function or class.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    function func() {}

    name(func); // 'func'
    example
    class Class {}

    name(Class); // 'Class'

    Parameters

    • func: AnyFunction<any[], any> | (new (...args: any[]) => any)

      The function or class to get the name for

    Returns string

    The name of func

  • omit<T, K>(object: T, keys: readonly K[]): Omit<T, K>
  • Create a copy of a provided object with the provided keys omitted. This is an implementation of the Omit<T, K> type in TypeScript.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const object = { a: 1, b: 2, c: 3 };

    omit(object, ['c']); // { a: 1, b: 2 }

    Type Parameters

    • T

    • K extends string | number | symbol

    Parameters

    • object: T

      The object you are renaming a key of

    • keys: readonly K[]

      The keys to remove from the object

    Returns Omit<T, K>

    A new object containing the entries that were not omitted

  • pick<T, K>(object: T, keys: readonly K[]): Pick<T, K>
  • From object, pick a set of properties whose keys are in the keys array. This is an implementation of the Pick<T, K> type in TypeScript.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    const object = { a: 1, b: 2, c: 3 };

    pick(object, ['a', 'b']); // { a: 1, b: 2 }

    Type Parameters

    • T

    • K extends string | number | symbol

    Parameters

    • object: T

      The object you are picking entries from

    • keys: readonly K[]

      The keys to keep from the object

    Returns Pick<T, K>

    A new object containing the picked entries

  • rename<T, K1, K2>(target: T, oldKey: _NonUnion<K1, K1>, newKey: _NonUnion<K2, K2>): Omit<T, K1 | K2> & Record<K2, T[K1]>
  • Create a copy of an object with a key renamed.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const object = { a: 1 };

    rename(object, 'a', 'b'); // { b: 1 }

    Type Parameters

    • T

    • K1 extends string | number | symbol

    • K2 extends PropertyKey

    Parameters

    • target: T
    • oldKey: _NonUnion<K1, K1>

      The key to rename

    • newKey: _NonUnion<K2, K2>

      The new name for the key

    Returns Omit<T, K1 | K2> & Record<K2, T[K1]>

    A shallow-copied object with the key name updated

Other Functions

  • identical<V>(a: readonly V[], b: readonly V[]): boolean
  • identical<V>(a: ReadonlySet<V>, b: ReadonlySet<V>): boolean
  • identical<K, V>(a: ReadonlyMap<K, V>, b: ReadonlyMap<K, V>): boolean
  • Check if 2 arrays have the same elements in the same order. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const a = [1, 2, 3];
    const b = [1, 2, 3];

    identical(a, b); // true

    Type Parameters

    • V

    Parameters

    • a: readonly V[]

      First array to compare

    • b: readonly V[]

      Second array to compare

    Returns boolean

    true if a and b have the same elements in the same order, false otherwise

  • Check if 2 Sets have the same elements. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const a = new Set([1, 2, 3]);
    const b = new Set([3, 2, 1]);

    identical(a, b); // true

    Type Parameters

    • V

    Parameters

    • a: ReadonlySet<V>

      First Set to compare

    • b: ReadonlySet<V>

      Second Set to compare

    Returns boolean

    true if a and b have the same elements, false otherwise

  • Check if 2 Maps have the same key-value pairs. Strict equality (===) is used to compare values.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    const a = new Map([['a', 1]]);
    const b = new Map([['a', 1]]);

    identical(a, b); // true

    Type Parameters

    • K

    • V

    Parameters

    • a: ReadonlyMap<K, V>

      First Map to compare

    • b: ReadonlyMap<K, V>

      Second Map to compare

    Returns boolean

    true if a and b have the key-value pairs, false otherwise

  • nullish(value: unknown): value is Nullish
  • Check if something is null or undefined.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const value = Math.random() > 0.5 ? 'hello' : null;

    nullish(value);

    Parameters

    • value: unknown

      Value to check

    Returns value is Nullish

    true if value is nullish, false if otherwise

  • same<T>(...iterables: readonly [Iterable<T>, Iterable<T>, Iterable<T>]): boolean
  • Check if 2 or more iterables hold the same elements. Strict equality (===) is used to compare elements.

    Time complexity: O(n) where n is the number of elements in the iterables

    Space complexity: O(n)

    example
    const a = [1, 2, 3];
    const b = [1, 2, 3];
    const c = [1, 2, 3];
    const d = [1, 2, 3];
    const e = [1, 2, 3];

    same(a, b, c, d, e); // true

    Type Parameters

    • T

    Parameters

    • Rest ...iterables: readonly [Iterable<T>, Iterable<T>, Iterable<T>]

      Elements to compare

    Returns boolean

    true if all elements are strictly equal, false otherwise

  • toDigits(value: number, precision: number): number
  • Round a number to n digits of precision after the decimal point.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const value = 12.345;

    toDigits(value, 2); // 12.35

    Parameters

    • value: number

      Value to format

    • precision: number

      Number of digits of precision after the decimal point

    Returns number

    Number rounded to the specified number of digits

Promise Functions

  • settled<E, T>(promise: PromiseLike<T>): Promise<Result<T, E>>
  • Settle a promise by returning a tuple of the resolved value or rejected error. This function never rejects.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const [value, error] = await settled(promise);
    

    Type Parameters

    • E

    • T

    Parameters

    • promise: PromiseLike<T>

      The promise to settle

    Returns Promise<Result<T, E>>

    A tuple of the resolved value or rejected error

  • timeout<T>(promise: PromiseLike<T>, timeoutMs: number): Promise<T>
  • Reject if the given promise does not resolve within the given timeout.

    Time complexity: O(1)

    Space complexity: O(1)

    Type Parameters

    • T

    Parameters

    • promise: PromiseLike<T>

      The promise to wait for

    • timeoutMs: number

      The timeout in milliseconds

    Returns Promise<T>

    The resolved value of the promise

Reducers Functions

  • max<A, B>(accumulator: A, currentValue: B): A | B
  • Get the largest value of the 2 parameters. Meant to be used with Array.prototype.reduce.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const array = [1, 2, 3];

    array.reduce(max); // 3

    Type Parameters

    Parameters

    • accumulator: A
    • currentValue: B

      The next value to compare

    Returns A | B

    previousValue or currentValue, whichever is larger

  • min<A, B>(accumulator: A, currentValue: B): A | B
  • Get the lowest value of the 2 parameters. Meant to be used with Array.prototype.reduce.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const array = [1, 2, 3];

    array.reduce(min); // 1

    Type Parameters

    Parameters

    • accumulator: A
    • currentValue: B

      The next value to compare

    Returns A | B

    previousValue or currentValue, whichever is lower

  • product(a: number, b: number): number
  • product(a: bigint, b: bigint): bigint
  • Calculate the product of 2 numbers. Meant to be used with Array.prototype.reduce.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const array = [1, 2, 3];

    array.reduce(product); // 6

    Parameters

    • a: number

      First factor

    • b: number

      Second factor

    Returns number

    The product of a and b

  • Calculate the product of 2 bigints. Meant to be used with Array.prototype.reduce.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const array = [1n, 2n, 3n];

    array.reduce(product); // 6n

    Parameters

    • a: bigint

      First factor

    • b: bigint

      Second factor

    Returns bigint

    The product of a and b

  • sum(a: number, b: number): number
  • sum(a: bigint, b: bigint): bigint
  • Calculate the sum of 2 numbers. Meant to be used with Array.prototype.reduce.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const array = [1, 2, 3];

    array.reduce(sum); // 6

    Parameters

    • a: number

      First summand

    • b: number

      Second summand

    Returns number

    The sum of a and b

  • Calculate the sum of 2 bigints. Meant to be used with Array.prototype.reduce.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    const array = [1n, 2n, 3n];

    array.reduce(sum); // 6n

    Parameters

    • a: bigint

      First summand

    • b: bigint

      Second summand

    Returns bigint

    The sum of a and b

Regular expressions Functions

  • regExpUnion(...regExps: RegExp[]): RegExp
  • Combines several regular expressions into a new one that matches any of them.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    regExpUnion(/[a-z]/, /\d/); // /([a-z])|(\d)/
    

    Parameters

    • Rest ...regExps: RegExp[]

      Regular expressions to get the union of

    Returns RegExp

    A new regular expression

Set Functions

  • difference<T>(a: Iterable<T>, b: Iterable<T>): Set<T>
  • Get a Set representing the difference of a and b (a \ b). The order of parameters matters.

    Time complexity: O(n)

    Space complexity: O(n)

    Type Parameters

    • T

    Parameters

    • a: Iterable<T>

      First iterable

    • b: Iterable<T>

      Second iterable

    Returns Set<T>

    A new Set which is the difference of a and b

  • intersection<T>(a: ReadonlySet<T>, b: ReadonlySet<T>): Set<T>
  • Get the intersection of 2 Sets.

    Time complexity: O(n)

    Space complexity: O(n)

    Type Parameters

    • T

    Parameters

    • a: ReadonlySet<T>

      First Set

    • b: ReadonlySet<T>

      Second Set

    Returns Set<T>

    A new Set which is the intersection of a and b

  • isDisjoint<T>(a: Iterable<T>, b: Iterable<T>): boolean
  • Check if a and b are disjoint. For best performance a should have more elements than b.

    Time complexity: O(n)

    Space complexity: O(1)

    Type Parameters

    • T

    Parameters

    • a: Iterable<T>

      First iterable

    • b: Iterable<T>

      Second iterable

    Returns boolean

    true if a and b are disjoint

  • isEmpty(map: ReadonlyMap<unknown, unknown>): map is ReadonlyMap<never, never>
  • isEmpty(map: Map<unknown, unknown>): map is Map<never, never>
  • isEmpty(set: ReadonlySet<unknown>): set is ReadonlySet<never>
  • isEmpty(set: Set<unknown>): set is Set<never>
  • isEmpty(string: string): string is ""
  • isEmpty(array: readonly unknown[]): array is readonly []
  • isEmpty(array: unknown[]): array is []
  • isEmpty(iterable: Iterable<unknown>): iterable is Iterable<never>
  • Check if a readonly Map is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Map([1, 2, 3])); // false
    
    example
    isEmpty(new Map()); // true
    

    Parameters

    • map: ReadonlyMap<unknown, unknown>

      The Map to check

    Returns map is ReadonlyMap<never, never>

    true if map is empty, false otherwise

  • Check if a Map is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Map([['a', 1], ['b', 2], ['c', 3]])); // false
    
    example
    isEmpty(new Map()); // true
    

    Parameters

    • map: Map<unknown, unknown>

      The Map to check

    Returns map is Map<never, never>

    true if map is empty, false otherwise

  • Check if a readonly Set is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Set([1, 2, 3])); // false
    
    example
    isEmpty(new Set()); // true
    

    Parameters

    • set: ReadonlySet<unknown>

      The Set to check

    Returns set is ReadonlySet<never>

    true if set is empty, false otherwise

  • Check if a Set is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Set([1, 2, 3])); // false
    
    example
    isEmpty(new Set()); // true
    

    Parameters

    • set: Set<unknown>

      The Set to check

    Returns set is Set<never>

    true if set is empty, false otherwise

  • Check if a string is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty('hello'); // false
    
    example
    isEmpty(''); // true
    

    Parameters

    • string: string

      The string to check

    Returns string is ""

    true if string is empty, false otherwise

  • Check if a readonly array is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • array: readonly unknown[]

      The array to check

    Returns array is readonly []

    true if array is empty, false otherwise

  • Check if an array is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • array: unknown[]

      The array to check

    Returns array is []

    true if array is empty, false otherwise

  • Check if an iterable is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • iterable: Iterable<unknown>

      The iterable to check

    Returns iterable is Iterable<never>

    true if iterable is empty, false otherwise

  • isSubset<T>(a: Iterable<T>, b: ReadonlySet<T>): boolean
  • Check if a is a subset of b.

    Time complexity: O(n)

    Space complexity: O(1)

    see

    isSuperset for checking if one Set is a superset of another

    Type Parameters

    • T

    Parameters

    • a: Iterable<T>

      First Set/iterable

    • b: ReadonlySet<T>

      Second Set

    Returns boolean

    true if a is a subset of b, false otherwise

  • isSuperset<T>(a: ReadonlySet<T>, b: Iterable<T>): boolean
  • Check if a is a superset of b.

    Time complexity: O(n)

    Space complexity: O(1)

    see

    isSubset for checking if one Set is a subset of another

    Type Parameters

    • T

    Parameters

    • a: ReadonlySet<T>

      First Set

    • b: Iterable<T>

      Second Set/iterable

    Returns boolean

    true if a is a superset of b, false otherwise

  • jaccardIndex<T>(a: ReadonlySet<T>, b: ReadonlySet<T>): number
  • Get the Jaccard index of 2 Sets.

    Time complexity: O(n)

    Space complexity: O(1)

    Type Parameters

    • T

    Parameters

    • a: ReadonlySet<T>

      First Set

    • b: ReadonlySet<T>

      Second Set

    Returns number

    The Jaccard index of a and b

  • symmetricDifference<A, B>(a: Iterable<A>, b: Iterable<B>): Set<A | B>
  • Get the symmetric difference of 2 iterables (a Δ b). For best performance a should have more elements than b.

    Time complexity: O(n)

    Space complexity: O(n)

    Type Parameters

    • A

    • B

    Parameters

    • a: Iterable<A>

      First iterable

    • b: Iterable<B>

      Second iterable

    Returns Set<A | B>

    A new Set which is the symmetric difference of a and b

  • union<A, B>(a: Iterable<A>, b: Iterable<B>): Set<A | B>
  • Get the union of 2 iterables. For best performance a should have more elements than b.

    Time complexity: O(n)

    Space complexity: O(n)

    Type Parameters

    • A

    • B

    Parameters

    • a: Iterable<A>

      First iterable

    • b: Iterable<B>

      Second iterable

    Returns Set<A | B>

    A new Set which is the union of a and b

Sort Functions

  • isSorted<T>(array: ArrayLike<T>, compareFn: ((a: T, b: T) => number)): boolean
  • Check whether an array is sorted according to a given compare function.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    import { Sort } from '@jonahsnider/util';

    const array = [1, 2, 3, 4, 5];

    isSorted(array, (a, b) => a - b);

    Type Parameters

    • T

    Parameters

    • array: ArrayLike<T>

      Array to check

    • compareFn: ((a: T, b: T) => number)

      Function to compare elements

        • (a: T, b: T): number
        • Parameters

          • a: T
          • b: T

          Returns number

    Returns boolean

    Whether the array is sorted according to the given compare function

  • sortObject<K, V>(object: Readonly<Record<K, V>>, compareFn: ((a: V, b: V) => number)): [K, V][]
  • Sort an object's keys by comparing their respective values.

    Time complexity: O(n)

    Space complexity: O(1)

    example
    import { Sort } from '@jonahsnider/util';

    const object = { a: 3, c: 1, b: 2 };

    Object.fromEntries(sortObject(object, Sort.ascending));

    Type Parameters

    • K extends PropertyKey

    • V

    Parameters

    • object: Readonly<Record<K, V>>

      Object to sort

    • compareFn: ((a: V, b: V) => number)

      Function used to compare object values

        • (a: V, b: V): number
        • Parameters

          • a: V
          • b: V

          Returns number

    Returns [K, V][]

    A new object with the keys in order

String Functions

  • capitalize<T>(text: T): Capitalize<T>
  • Capitalizes the first letter of a string.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    capitalize('hello'); // 'Hello'
    
    see

    uncapitalize for the inverse operation

    Type Parameters

    • T extends string

    Parameters

    • text: T

      Text to capitalize

    Returns Capitalize<T>

    Capitalized string

  • isAnagram<T>(a: ArrayLike<T> & Iterable<T>, b: ArrayLike<T> & Iterable<T>): boolean
  • Check if 2 strings are anagrams of each other. Case-sensitive.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    isAnagram('abc', 'cba'); // true
    
    example
    isAnagram('abc', 'Cba'); // false
    

    Type Parameters

    • T

    Parameters

    • a: ArrayLike<T> & Iterable<T>

      First string to compare

    • b: ArrayLike<T> & Iterable<T>

      Second string to compare

    Returns boolean

    Whether the strings are anagrams of each other

  • isEmpty(map: ReadonlyMap<unknown, unknown>): map is ReadonlyMap<never, never>
  • isEmpty(map: Map<unknown, unknown>): map is Map<never, never>
  • isEmpty(set: ReadonlySet<unknown>): set is ReadonlySet<never>
  • isEmpty(set: Set<unknown>): set is Set<never>
  • isEmpty(string: string): string is ""
  • isEmpty(array: readonly unknown[]): array is readonly []
  • isEmpty(array: unknown[]): array is []
  • isEmpty(iterable: Iterable<unknown>): iterable is Iterable<never>
  • Check if a readonly Map is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Map([1, 2, 3])); // false
    
    example
    isEmpty(new Map()); // true
    

    Parameters

    • map: ReadonlyMap<unknown, unknown>

      The Map to check

    Returns map is ReadonlyMap<never, never>

    true if map is empty, false otherwise

  • Check if a Map is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Map([['a', 1], ['b', 2], ['c', 3]])); // false
    
    example
    isEmpty(new Map()); // true
    

    Parameters

    • map: Map<unknown, unknown>

      The Map to check

    Returns map is Map<never, never>

    true if map is empty, false otherwise

  • Check if a readonly Set is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Set([1, 2, 3])); // false
    
    example
    isEmpty(new Set()); // true
    

    Parameters

    • set: ReadonlySet<unknown>

      The Set to check

    Returns set is ReadonlySet<never>

    true if set is empty, false otherwise

  • Check if a Set is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty(new Set([1, 2, 3])); // false
    
    example
    isEmpty(new Set()); // true
    

    Parameters

    • set: Set<unknown>

      The Set to check

    Returns set is Set<never>

    true if set is empty, false otherwise

  • Check if a string is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty('hello'); // false
    
    example
    isEmpty(''); // true
    

    Parameters

    • string: string

      The string to check

    Returns string is ""

    true if string is empty, false otherwise

  • Check if a readonly array is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • array: readonly unknown[]

      The array to check

    Returns array is readonly []

    true if array is empty, false otherwise

  • Check if an array is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • array: unknown[]

      The array to check

    Returns array is []

    true if array is empty, false otherwise

  • Check if an iterable is empty.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isEmpty([1, 2, 3]); // false
    
    example
    isEmpty([]); // true
    

    Parameters

    • iterable: Iterable<unknown>

      The iterable to check

    Returns iterable is Iterable<never>

    true if iterable is empty, false otherwise

  • isWhitespace(string: string): boolean
  • Check whether a string is empty or whitespace.

    Time complexity: O(1)

    Space complexity: O(1)

    example
    isWhitespace(' \n '); // true
    
    example
    isWhitespace(''); // true
    

    Parameters

    • string: string

      String to check

    Returns boolean

    Whether the string is whitespace

  • lines(string: string): string[]
  • Get each line in a string. Works with LF and CRLF line endings.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    lines('a\nb\r\nc'); // ['a', 'b', 'c']
    

    Parameters

    • string: string

      String to get the lines of

    Returns string[]

    An array of lines

  • multiReplace(string: string, replacements: Record<string, string>): string
  • A string replacement function, but specialized for doing multiple replacements in a single pass through the input string.

    Based off Nim's strutils.multiReplace.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    multiReplace('a b c', {a: 'c', c: 'a'}); // 'c b a'
    

    Parameters

    • string: string

      The string to replace values in

    • replacements: Record<string, string>

      An object of replacements where keys are the search values and values are the replacement values

    Returns string

    A new string with the replacements applied

  • trimEnd(string: string, end: string): string
  • trimEnd<T>(array: readonly T[], end: T): T[]
  • Removes the trailing end characters from a string.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    trimEnd('aabbcc', 'c'); // 'aabb'
    
    see

    {@link (trimStart:1)} to do the same thing but trim from the start of a string

    Parameters

    • string: string

      The string to trim

    • end: string

      The character to remove from the end of string

    Returns string

    A string with the leading end characters removed

  • Removes the trailing end characters from an array.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    trimEnd(['a', 'a', 'b', 'b', 'c', 'c'], 'c'); // ['a', 'a', 'b', 'b']
    
    see

    {@link (trimStart:2)} to do the same thing but trim from the start of an array

    Type Parameters

    • T

    Parameters

    • array: readonly T[]

      The array to trim

    • end: T

      The character to remove from the end of array

    Returns T[]

    A shallow-copied array with the trailing start characters removed

  • trimStart(string: string, start: string): string
  • trimStart<T>(array: readonly T[], start: T): T[]
  • Removes the leading start characters from a string.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    trimStart('aabbcc', 'a'); // 'bbcc'
    
    see

    {@link (trimEnd:1)} to do the same thing but trim from the end of a string

    Parameters

    • string: string

      The string to trim

    • start: string

      The character to remove from the start of string

    Returns string

    A string with the leading start characters removed

  • Removes the leading start characters from an array.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    trimStart(['a', 'a', 'b', 'b', 'c', 'c'], 'a'); // ['b', 'b', 'c', 'c']
    
    see

    {@link (trimEnd:2)} to do the same thing but trim from the end of an array

    Type Parameters

    • T

    Parameters

    • array: readonly T[]

      The array to trim

    • start: T

      The character to remove from the start of array

    Returns T[]

    A shallow-copied array with the leading start characters removed

  • truncate<T>(text: T, maxLength: number, suffix?: string): T | `${string}${typeof suffix}`
  • Truncate text to a certain length, optionally appending a suffix when truncated.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    truncate('hello, world', 5, '...'); // 'hello...'
    

    Type Parameters

    • T extends string

    Parameters

    • text: T

      Text to truncate

    • maxLength: number

      Maximum length before text is truncated

    • suffix: string = ''

      Suffix to append if text was truncated

    Returns T | `${string}${typeof suffix}`

    Truncated text

  • uncapitalize<T>(text: T): Uncapitalize<T>
  • Uncapitalizes the first letter of a string.

    Time complexity: O(n)

    Space complexity: O(n)

    example
    uncapitalize('HELLO'); // hELLO
    
    see

    capitalize for the inverse operation

    Type Parameters

    • T extends string

    Parameters

    • text: T

      Text to uncapitalize

    Returns Uncapitalize<T>

    Uncapitalized string

Generated using TypeDoc