Options
All
  • Public
  • Public/Protected
  • All
Menu

Module core

Index

Array Functions

Boolean Functions

Function Functions

Logic Functions

Number Functions

Object Functions

Other Functions

Promise Functions

String Functions

Array Functions

Const all

  • all<T>(predicate: (value: T, index: number) => boolean): (array: T[]) => boolean
  • Finally returns true if predicate returns true for all elements in array, else returns false.

    memberof

    core

    since

    0.1.0

    see

    any

    example
    all(v => v > 0)([]) //=> true
    all(v => v > 0)([1, 2, 3]) //=> true
    all(v => v > 0)([-1, 2, 3]) //=> false
    all(v => v as number > 0)([-1, '1']) //=> true
    

    Type parameters

    • T

    Parameters

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

      Returns true to indicate value passes evaluation, else returns false.

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

          • value: T
          • index: number

          Returns boolean

    Returns (array: T[]) => boolean

    Finally returns true if predicate returns true for all elements in array, else returns false.

      • (array: T[]): boolean
      • Parameters

        • array: T[]

          Array to test.

        Returns boolean

Const allFalse

  • allFalse(array: any[]): boolean
  • Returns true if all elements in array are false, else returns false.

    memberof

    core

    since

    0.1.0

    see

    all allTrue

    example
    allFalse([]) //=> true
    allFalse([true]) //=> false
    allFalse([false]) //=> true
    allFalse([true, false]) //=> false
    

    Parameters

    • array: any[]

      Array to test.

    Returns boolean

    true if all elements in array are false, else returns false

Const allNotNil

  • allNotNil(array: any[]): boolean
  • Returns true if all elements in array are not null or undefined, else returns false.

    memberof

    core

    since

    0.1.0

    see

    all

    example
    allNotNil([]) //=> true
    allNotNil([1]) //=> true
    allNotNil([1, 2]) //=> true
    allNotNil([1, 'a']) //=> true
    allNotNil([1, null]) //=> false
    allNotNil([1, undefined]) //=> false
    

    Parameters

    • array: any[]

      Array to test.

    Returns boolean

    true if all elements in array are not null or undefined, else returns false.

Const allTrue

  • allTrue(array: any[]): boolean
  • Returns true if all elements in array are true, else returns false.

    memberof

    core

    since

    0.1.0

    see

    all allFalse

    example
    allTrue([]) //=> true
    allTrue([true]) //=> true
    allTrue([false]) //=> false
    allTrue([true, false]) //=> false
    

    Parameters

    • array: any[]

      Array to test.

    Returns boolean

    true if all elements in array are true, else returns false.

Const any

  • any<T>(predicate: (value: T, index: number) => boolean): (array: T[]) => boolean
  • Finally returns true if predicate returns true for at least 1 element in array, else returns false.

    memberof

    core

    since

    0.1.0

    see

    all anyFalse anyNil anyTrue

    example
    any(v => v > 0)([]) //=> false
    any(v => v > 0)([-1, -2, 3]) //=> true
    any(v => v > 0)([-1, -2, -3]) //=> false
    any(v => v as number > 0)([1, 'a']) //=> true
    

    Type parameters

    • T

    Parameters

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

      Returns true to indicate value passes evaluation, else returns false.

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

          • value: T
          • index: number

          Returns boolean

    Returns (array: T[]) => boolean

    Finally returns true if predicate returns true for at least 1 element in array, else returns false.

      • (array: T[]): boolean
      • Parameters

        • array: T[]

          Array to test.

        Returns boolean

Const anyFalse

  • anyFalse(array: any[]): boolean
  • Returns true if at least 1 element in array is false, else returns false.

    memberof

    core

    since

    0.1.0

    see

    any anyTrue

    example
    anyFalse([]) //=> false
    anyFalse([true, false]) //=> true
    anyFalse([true, true]) //=> false
    

    Parameters

    • array: any[]

      Array to test.

    Returns boolean

    true if at least 1 element in array is false, else returns false.

Const anyNil

  • anyNil(array: any[]): boolean
  • Returns true if all elements in array are true, else returns false.

    memberof

    core

    since

    0.1.0

    see

    any

    example
    anyNil([]) //=> false
    anyNil([1, 2]) //=> false
    anyNil([1, null]) //=> true
    anyNil([1, undefined]) //=> true
    

    Parameters

    • array: any[]

      Array to test.

    Returns boolean

    true if all elements in array are true, else returns false.

Const anyTrue

  • anyTrue(array: any[]): boolean
  • Returns true if at least 1 element in array is true, else returns false.

    memberof

    core

    since

    0.1.0

    see

    any anyFalse

    example
    anyTrue([]) //=> false
    anyTrue([true, false]) //=> true
    anyTrue([false, false]) //=> false
    

    Parameters

    • array: any[]

      Array to test.

    Returns boolean

    true if at least 1 element in array is true, else returns false.

Const arrayIf

  • arrayIf<T>(predicate: (array: T[]) => boolean, defaultArray?: T[]): (array: T[]) => T[]
  • Finally returns array if predicate returns true, else returns defaultArray (optional, defaults to empty array).

    memberof

    core

    since

    0.1.0

    see

    valueIf

    example
    arrayIf(array => array.includes(4), [1])([1, 2, 3]); //=> [1]
    arrayIf(array => array.includes(2), [1])([1, 2, 3]); //=> [1, 2, 3]
    

    Type parameters

    • T

    Parameters

    • predicate: (array: T[]) => boolean

      Boolean function to determine which array to return.

        • (array: T[]): boolean
        • Parameters

          • array: T[]

          Returns boolean

    • defaultArray: T[] = []

      The default array to return.

    Returns (array: T[]) => T[]

    Finally returns array if predicate returns true, else returns defaultArray.

      • (array: T[]): T[]
      • Parameters

        • array: T[]

        Returns T[]

Const arrayOr

  • arrayOr<T>(defaultArray?: T[]): (array: any) => T[]
  • Finally returns array if it is valid via isArray, else returns defaultArray.

    memberof

    core

    since

    0.1.0

    see

    valueIf arrayIf

    example
    arrayOr()(null); //=> [] as unknown[]
    arrayOr([1])(null); //=> [1]
    arrayOr([1])([1, 2, 3]); //=> [1, 2, 3]
    

    Type parameters

    • T

    Parameters

    • defaultArray: T[] = []

      Default array to return.

    Returns (array: any) => T[]

    Finally returns array if it is valid via isArray, else returns defaultArray.

      • (array: any): T[]
      • Parameters

        • array: any

          Array to test.

        Returns T[]

Const atIndex

  • atIndex(index: number): <T>(array: T[]) => T
  • Finally returns the element at index if found in array, else returns undefined.

    memberof

    core

    since

    0.1.0

    example
     atIndex(0)([]); //=> undefined
     atIndex(0)([1, 2, 3]); //=> 1
     atIndex(1)([1, 2, 3]); //=> 2
     atIndex(0)([1, 'a', 2]); //=> 1
    

    Parameters

    • index: number

      Index of element in array to return.

    Returns <T>(array: T[]) => T

    Finally returns the element at index if found in array, else returns undefined.

      • <T>(array: T[]): T
      • Type parameters

        • T

        Parameters

        • array: T[]

          Array to get an element from.

        Returns T

Const atRandom

  • atRandom<T>(array: T[]): undefined | T
  • Returns undefined if array has no elements, else returns a random element from array.

    memberof

    core

    since

    0.1.0

    see

    atIndex

    example
     atRandom([]); //=> undefined
     atRandom([1, 2, 3]); //=> v where [1, 2, 3].includes(v)
     atRandom([1, 'a', 2]); //=> v where [1, 2, 3].includes(v)
    

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to get an element from.

    Returns undefined | T

    Returns undefined if array has no elements, else returns a random element from array.

Const coalesce

  • coalesce<T>(array: T[]): undefined | T
  • Returns the first non-null, non-undefined element in array, else returns undefined.

    memberof

    core

    since

    0.1.0

    see

    compact

    example
     coalesce([]); //=> undefined
     coalesce([null, undefined, 1]); //=> 1
    

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to use.

    Returns undefined | T

    The first non-null, non-undefined element in array, else returns undefined.

Const compact

  • compact<T>(array: T[]): T[]
  • Returns an array containing only truthy values from array.

    memberof

    core

    since

    0.1.0

    see

    coalesce

    example
    compact([]); //=> []
    compact([null, undefined, [], '', 'a', 0, 1, 0.1, true, false, {}, { a: 1 }]); //=> [[], 'a', 1, 0.1, true, {}, { a: 1 }]
    

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to use.

    Returns T[]

    Returns an array containing only truthy values from array.

Const concat

  • concat<T>(array1: T[]): <U>(array2: U[]) => (T | U)[]
  • Finally returns an array containing all elements in array1 and array2 (includes duplicates).

    memberof

    core

    since

    0.1.0

    see

    union

    example
    concat([])([]); //=> []
    concat([1, 2])([3, 4]); //=> [1, 2, 3, 4]
    concat([1, 'a'])(['b', 2]); //=> [1, 'a', 'b', 2]
    

    Type parameters

    • T

    Parameters

    • array1: T[]

      Array to add elements to.

    Returns <U>(array2: U[]) => (T | U)[]

    Finally returns an array containing all elements in array1 and array2 (includes duplicates).

      • <U>(array2: U[]): (T | U)[]
      • Type parameters

        • U

        Parameters

        • array2: U[]

          Array to add elements from.

        Returns (T | U)[]

Const count

  • count<T>(array: T[]): number
  • Returns the number of elements in array.

    memberof

    core

    since

    0.1.0

    see

    countIs countIsAny countIsNone

    example
    count([]); //=> 0
    count([1, 2, 3]); //=> 3
    

    Type parameters

    • T

    Parameters

    • array: T[]

      The array to count.

    Returns number

    Returns the number of elements in array.

Const countIs

  • countIs(count: number): <T>(array: T[]) => boolean
  • Finally returns true if array's count is equal to count, else returns false.

    memberof

    core

    since

    0.1.0

    see

    count countIsAny countIsNone

    example
    count(0)([]); //=> true
    count(3)([1, 2, 3]); //=> true
    count(4)([1, 2, 3]); //=> false
    

    Parameters

    • count: number

      The expected count.

    Returns <T>(array: T[]) => boolean

    Finally returns true if array's count is equal to count, else returns false.

      • <T>(array: T[]): boolean
      • Type parameters

        • T

        Parameters

        • array: T[]

        Returns boolean

Const countIsAny

  • countIsAny<T>(array: T[]): boolean
  • Returns true if array's count is greater than 0, else returns false.

    memberof

    core

    since

    0.1.0

    see

    count countIsNone

    count([]); //=> false
    count([1, 2, 3]); //=> true
    

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to test.

    Returns boolean

    true if array's count is greater than 0, else returns false.

Const countIsNone

  • countIsNone<T>(array: T[]): boolean
  • Returns true if array's count is equal to 0, else returns false.

    memberof

    core

    since

    0.1.0

    see

    count countIsAny

    count([]); //=> true
    count([1, 2, 3]); //=> false
    

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to test.

    Returns boolean

    true if array's count is equal to 0, else returns false.

Const difference

  • difference(array1: any[]): (array2: any[]) => any[]
  • Finally returns all elements in array2 that are not present in array1 (i.e., returns the difference of array2 - array1).

    memberof

    core

    since

    0.1.0

    see

    intersection

    example
    difference([])([]) //=> []
    difference([])([1, 2, 3]) //=> [1, 2, 3]
    difference([1])([1]) //=> []
    difference([1])([1, 2]) //=> [2]
    difference([1])([3, 4]) //=> [3, 4]
    difference([1, 'a'])([1, 'b']) //=> ['b']
    

    Parameters

    • array1: any[]

      Array to subtract.

    Returns (array2: any[]) => any[]

    Finally returns all elements in array2 that are not present in array1

      • (array2: any[]): any[]
      • Parameters

        • array2: any[]

          Array to subtract from.

        Returns any[]

Const excludes

  • excludes(...elements: any[]): <T>(array: T[]) => boolean
  • Inverse of includes. I.e., returns true if array does not include all elements, else returns false.

    memberof

    core

    since

    0.1.0

    see

    includes

    example
    excludes()([]) //=> true
    excludes()([1, 2, 3]) //=> true
    excludes(4)([1, 2, 3]) //=> true
    excludes(1)([1, 2, 3]) //=> false
    excludes(1, 2)([1, 2, 3]) //=> false
    

    Parameters

    • Rest ...elements: any[]

      Array of elements to check are excluded.

    Returns <T>(array: T[]) => boolean

    true if array does not include all elements, else returns false.

      • <T>(array: T[]): boolean
      • Type parameters

        • T

        Parameters

        • array: T[]

          Array to test.

        Returns boolean

Const fill

  • fill<TFiller, TArray>(filler: TFiller, options?: FillOptions): (array: TArray[]) => (TFiller | TArray)[]
  • Finally returns array filled with a filler value starting from FillOptions.start to FillOptions.end.

    example
    fill('a', { start: 1, end: 2 })([1, 2, 3, 4]); //=> [1, 'a', 'a', 4]
    

    If FillOptions.end exceeds array.length then array's length will be increased to equal FillOptions.end before filling.

    example
    // Note the array's length is less than `end` hence the array is extended to
    // match `end` before filling.
    fill('a', { end: 3 })([]); //=> ['a', 'a', 'a']
    
    memberof

    core

    since

    0.1.0

    see

    fillRecursive

    Type parameters

    • TFiller

    • TArray

    Parameters

    • filler: TFiller

      Value to fill array with.

    • options: FillOptions = {}

    Returns (array: TArray[]) => (TFiller | TArray)[]

    Finally returns array filled with a filler value starting from FillOptions.start to FillOptions.end.

      • (array: TArray[]): (TFiller | TArray)[]
      • Parameters

        • array: TArray[]

        Returns (TFiller | TArray)[]

Const fillRecursive

  • fillRecursive<TFiller, TArray>(transformer: (prev: TFiller | TArray) => TFiller, total: number): (array: (TFiller | TArray)[]) => (TFiller | TArray)[]
  • Finally returns array filled recursively where a total number subsequent elements are provided by a transformer that receives the previous element.

    memberof

    core

    since

    0.1.0

    example
    fillRecursive(prev => prev * 2, 4)([]); //=> []
    fillRecursive(prev => prev * 2, 4)([1]); //=> [1, 2, 4, 8, 16]
    fillRecursive(prev => prev * 2, 4)([1, 2]); //=> [1, 2, 4, 8, 16, 32]
    

    Type parameters

    • TFiller

    • TArray

    Parameters

    • transformer: (prev: TFiller | TArray) => TFiller

      Returns a new value for prev.

        • (prev: TFiller | TArray): TFiller
        • Parameters

          • prev: TFiller | TArray

          Returns TFiller

    • total: number

      Number of elements to fill array with.

    Returns (array: (TFiller | TArray)[]) => (TFiller | TArray)[]

    Finally returns array filled recursively with elements provided by transformer.

      • (array: (TFiller | TArray)[]): (TFiller | TArray)[]
      • Parameters

        • array: (TFiller | TArray)[]

        Returns (TFiller | TArray)[]

Const filter

  • filter<T>(predicate: (value: T, index: number) => boolean): (array: T[]) => T[]
  • Finally returns array elements where predicate returns true.

    memberof

    core

    since

    0.1.0

    see

    filterEntries filterNot filterMap filterPart includes excludes

    example
    filter((v) => v > 0)([]) //=> []
    filter((v) => v > 0)([-1, 2, 3]) //=> [2, 3]
    filter((v) => v as number > 0)([1, '2', -3]) //=> [1, '2']
    

    Type parameters

    • T

    Parameters

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

      Returns true to keep value, else returns false to omit value.

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

          • value: T
          • index: number

          Returns boolean

    Returns (array: T[]) => T[]

    Finally returns array elements where predicate returns true.

      • (array: T[]): T[]
      • Parameters

        • array: T[]

          Array to filter.

        Returns T[]

Const filterMap

  • filterMap<TArray, TMapped>(transformer: (value: TArray, index: number) => TArray | TMapped, options?: FilterMapOptions<TArray, TMapped>): (array: TArray[]) => (TArray | TMapped)[]
  • Returns a filtered & transformed array by sequentially applying filter, map, and filter to each element in 1 iteration to improve performance rather than manually chaining these operations (which would result in several iterations).

    I.e., keeps array elements where FilterMapOptions.preFilter (optional, defaults to return true) is true, then uses transformer to return new elements, and finally keeps elements where FilterMapOptions.postFilter (optional, defaults to return true) is true.

    Note: Filters will affect the provided index for transformer, e.g., if 'a' is preFiltered from ['a', 'b'] then transformer receives index 0 for b.

    memberof

    core

    since

    0.1.0

    see

    filter map

    example
    // Pre- and post- filter:
    const noAPredicate = (v: string) => !v.includes('a');
    const noCPredicate = (v: string) => !v.includes('c');
    const appendDTransformer = (v: string) => v + 'd';
    filterMap(appendDTransformer, { preFilter: noAPredicate, postFilter: noCPredicate })([]) //=> []
    filterMap(appendDTransformer, { preFilter: noAPredicate, postFilter: noCPredicate })(['a', 'b', 'c']) //=> ['bd']
    
    // Pre-filter:
    const positivePredicate = (v: number) => v > 0;
    const incrementTransformer = (v: number) => v + 1;
    filterMap(incrementTransformer, { preFilter: positivePredicate })([-1, 2, 3]) //=> [3, 4]
    // Post-filter:
    filterMap(incrementTransformer, { postFilter: positivePredicate }) //=> [3, 4]
    

    Type parameters

    • TArray

    • TMapped

    Parameters

    • transformer: (value: TArray, index: number) => TArray | TMapped

      Applied after options.preFilter (if value is kept) and before options.postFilter, returns a new value, see map.

        • (value: TArray, index: number): TArray | TMapped
        • Parameters

          • value: TArray
          • index: number

          Returns TArray | TMapped

    • options: FilterMapOptions<TArray, TMapped> = {}

    Returns (array: TArray[]) => (TArray | TMapped)[]

    Finally returns array after applying a pre-filter, transformation, & post-filter.

      • (array: TArray[]): (TArray | TMapped)[]
      • Parameters

        • array: TArray[]

        Returns (TArray | TMapped)[]

Const filterNot

  • filterNot<T>(predicate: (value: T, index: number) => boolean): (array: T[]) => T[]
  • Inverse of filter, i.e., finally returns array with elements where predicate returns false.

    memberof

    core

    since

    0.1.0

    see

    excludes filter negate

    example
    filterNot((v) => v > 0)([]) //=> []
    filterNot((v) => v > 0)([-1, 2, 3]) //=> [-1]
    filterNot((v) => v as number > 0)([1, '2', -3]) //=> [-3]
    

    Type parameters

    • T

    Parameters

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

      Returns false to keep value, else returns true to omit value.

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

          • value: T
          • index: number

          Returns boolean

    Returns (array: T[]) => T[]

    Finally returns array with elements where predicate returns false.

      • (array: T[]): T[]
      • Parameters

        • array: T[]

          Array to filter.

        Returns T[]

Const filterPart

  • filterPart<T>(predicate: (value: T, index: number) => boolean): (array: T[]) => T[][]
  • Combines filter & filterNot to finally return a 2D array where the first array contains the kept elements whilst the second array contains the remaining elements (that are usually omitted in filter).

    memberof

    core

    since

    0.1.0

    see

    filter filterNot takePart

    example
    const isEven = n => n % 2 === 0;
    filterPart(isEven)([]) //=> [[], []]
    filterPart(isEven)([1, 2, 3, 4]) //=> [[2, 4], [1, 3]]
    filterPart(isEven)([1, '2', 3, 4]) //=> [['2', 4], [1, 3]
    

    Type parameters

    • T

    Parameters

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

      Returns true to keep value, else returns false to omit value.

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

          • value: T
          • index: number

          Returns boolean

    Returns (array: T[]) => T[][]

    Finally returns an array containing 2 arrays of the form [...kept, ...omitted].

      • (array: T[]): T[][]
      • Parameters

        • array: T[]

          Array to filter.

        Returns T[][]

Const findOr

  • findOr<T, U>(defaultValue: U, predicate: (value: T, index: number) => boolean): (array: T[]) => T | U
  • Finally returns the element where predicate is true, else returns defaultValue.

    memberof

    core

    since

    0.1.0

    example
    findOr(4, (v: number) => v > 0)([]) //=> 4
    findOr(4, (v: number) => v > 0)([-1, -2, 3]) //=> 3
    findOr(4, (v) => v > 0)([-1, -2, -3]) //=> 4
    findOr(4, (v) => v as number > 0)([-1, 'a', -3]) //=> 4
    

    Type parameters

    • T

    • U

    Parameters

    • defaultValue: U

      Value to return when predicate returns false.

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

      Returns true to indicate the value passes evaluation (i.e., matches the search), else returns false to indicate value fails evaluation.

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

          • value: T
          • index: number

          Returns boolean

    Returns (array: T[]) => T | U

    Finally returns the element where predicate is true, else returns defaultValue.

      • (array: T[]): T | U
      • Parameters

        • array: T[]

        Returns T | U

Const groupBy

  • groupBy<TItem, TItemTransformed, TAggregate>(keySelector: (item: TItem) => string, options?: GroupByOptions<TItem, TItemTransformed, TAggregate>): (items: TItem[]) => Record<string, TItem[]> | Record<string, TItemTransformed[]> | Record<string, TAggregate>
  • Restricts a given value to be inclusively within the range of min to max.

    memberof

    core

    since

    1.0.0

    example
    interface Pet { name: string; age: number };
    const pets: Pet[] = [{ name: 'pet1', age: 1 }, { name: 'pet2', age: 2 }, { name: 'pet3', age: 2 }];
    const byAge = (p: Pet) => p.age;
    // Group `pets` by their `name`.
    groupBy(byAge)(pets); //=> {1: [{ name: 'pet1', age: 1 }], 2: [ { name: 'pet2', age: 2 }, { name: 'pet3', age: 2 }]}
    const withName = (p: Pet) => p.name;
    // Group `pets` by `name` & map items to their name
    groupBy(byAge, { itemTransformer: withName)(pets); //=> {1: ['pet1'], 2: ['pet2', 'pet3']}
    const sumAges = (ageGroup: string, ages) => sum(ages as number[]);
    // Group `pets` by `name` & map groups to a summed value.
    groupBy(byAge, { aggregateTransformer: sumAges)(pets); //=> {1: 1, 2: 4}
    

    Type parameters

    • TItem

    • TItemTransformed

    • TAggregate

    Parameters

    • keySelector: (item: TItem) => string

      Item key to group by.

        • (item: TItem): string
        • Parameters

          • item: TItem

          Returns string

    • Optional options: GroupByOptions<TItem, TItemTransformed, TAggregate>

    Returns (items: TItem[]) => Record<string, TItem[]> | Record<string, TItemTransformed[]> | Record<string, TAggregate>

    Finally returns an object mapping keys to either a group of items (via itemTransformer) or an aggregate value (via aggregateTransformer).

      • (items: TItem[]): Record<string, TItem[]> | Record<string, TItemTransformed[]> | Record<string, TAggregate>
      • Parameters

        • items: TItem[]

        Returns Record<string, TItem[]> | Record<string, TItemTransformed[]> | Record<string, TAggregate>

Const head

  • head<T>(array: T[]): T
  • Returns the first element of array if found else returns undefined.

    memberof

    core

    since

    0.1.0

    alias

    first

    see

    init atIndex last tail

    example
     head([]); //=> undefined
     head([1, 2, 3]); //=> 1
    

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to use.

    Returns T

    The first element of array if found else returns undefined.

Const includes

  • includes(...elements: any[]): <T>(array: T[]) => boolean
  • Finally returns true if array includes all elements, else returns false.

    memberof

    core

    since

    0.1.0

    see

    excludes filter

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

    Parameters

    • Rest ...elements: any[]

      The elements to check for.

    Returns <T>(array: T[]) => boolean

    Finally returns true if array includes all elements, else returns false.

      • <T>(array: T[]): boolean
      • Type parameters

        • T

        Parameters

        • array: T[]

          Array to test.

        Returns boolean

Const indexOf

  • indexOf(element: any): <T>(array: T[]) => number
  • Finally returns the index of element if found in array, else returns -1.

    memberof

    core

    since

    0.1.0

    example
     indexOf()([]); //=> -1
     indexOf(1)([]); //=> -1
     indexOf(1)([1]); //=> 0
     indexOf(2)([1, 2]); //=> 1
    

    Parameters

    • element: any

      Element to search for.

    Returns <T>(array: T[]) => number

    Index of element if found in array, else returns -1.

      • <T>(array: T[]): number
      • Type parameters

        • T

        Parameters

        • array: T[]

          Array to search in.

        Returns number

Const init

  • init<T>(array: T[]): T[]
  • Returns array without the last element.

    memberof

    core

    since

    0.1.0

    see

    head last tail

    example
     init([]); //=> []
     init([1, 2, 3]); //=> [1, 2]
     init([1, 'a', true]); //=> [1, 'a']
    

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to use.

    Returns T[]

    Returns array without the last element.

Const intersection

  • intersection(array1: any[]): (array2: any[]) => any[]
  • Finally returns elements present in both array1 and array2.

    memberof

    core

    since

    0.1.0

    example
    intersection([])([]) //=> []
    intersection([])([1, 2, 3]) //=> []
    intersection([1])([1]) //=> [1]
    intersection([1, 2])([1, 2]) //=> [1, 2]
    intersection([1, 2])([3, 4]) //=> []
    intersection([1, 'a'])([1, 'b']) //=> [1]
    

    Parameters

    • array1: any[]

      Second array to test.

    Returns (array2: any[]) => any[]

    Finally returns elements present in both array1 and array2.

      • (array2: any[]): any[]
      • Parameters

        • array2: any[]

        Returns any[]

Const isArray

  • isArray(value: any): boolean
  • Returns true if value is an array, else returns false.

    memberof

    core

    since

    0.1.0

    see

    isObject

    example
    isArray(null); //=> false
    isArray([]); //=> true
    isArray([1, 2, 3]); //=> true
    

    Parameters

    • value: any

      Value to test.

    Returns boolean

    true if value is an array, else returns false

Const join

  • join(delimiter?: string): <T>(value: T[]) => string
  • Inverse of split, i.e., Finally returns a string containing elements from array delimited by delimiter (optional, defaults to ,)

    memberof

    core

    since

    0.1.0

    see

    split

    example
    join('')([]); //=> []
    join()(['foo', 'bar', 'baz']); //=> 'foo bar baz'
    join(' ')(['foo', 'bar', 'baz']); //=> 'foo bar baz'
    join('')(['f', 'o', 'o']); //=> 'foo'
    

    Parameters

    • delimiter: string = ','

    Returns <T>(value: T[]) => string

    Finally returns a string elements from array that are delimited by delimiter.

      • <T>(value: T[]): string
      • Type parameters

        • T

        Parameters

        • value: T[]

        Returns string

Const keyBy

  • keyBy<T>(selector: (element: T) => string): (array: T[]) => Record<string, T>
  • Uses selector to generate a string key from array elements, then finally returns a Record containing entries where each element becomes the value to the key it provided.

    Elements that provide an invalid key (e.g., undefined) are omitted.

    memberof

    core

    since

    0.1.0

    example
     keyBy(v => v.name)([]); //=> {}
     keyBy(v => v.name)([{ name: 'a', orders: 1 }, , { name: 'b' }]); //=> { a: { name: 'a', orders: 1 }, b: { name: 'b' } }
     keyBy(v => v.orders)([{ name: 'a', orders: 1 }, , { name: 'b' }]); //=> { a: { name: 'a', orders: 1 } }
    

    Type parameters

    • T: Record<string, any>

    Parameters

    • selector: (element: T) => string

      Returns a key for element that will form an entry in the returned object.

        • (element: T): string
        • Parameters

          • element: T

          Returns string

    Returns (array: T[]) => Record<string, T>

    Finally returns a Record containing entries where each element becomes the value to the key it provided.

      • (array: T[]): Record<string, T>
      • Parameters

        • array: T[]

        Returns Record<string, T>

Const last

  • last<T>(array: T[]): T
  • Returns the last element of array if it exists else returns undefined.

    memberof

    core

    since

    0.1.0

    example
     last([]); //=> undefined
     last([1, 2, 3]); //=> 3
    

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to use.

    Returns T

    The last element of array if it exists else returns undefined.

Const map

  • map<T, U>(transformer: (value: T, index: number) => U): (array: T[]) => U[]
  • Finally returns array containing elements mapped using transformer to provide the new value.

    memberof

    core

    since

    0.1.0

    example
    map((v) => v * 2)([]) //=> []
    map((v) => v * 2)([1, 2, 3]) //=> [2, 4, 6]
    map((v) => v * 2)([1, '2']) //=> [2, 4]
    

    Type parameters

    • T

    • U

    Parameters

    • transformer: (value: T, index: number) => U

      Returns a new value.

        • (value: T, index: number): U
        • Parameters

          • value: T
          • index: number

          Returns U

    Returns (array: T[]) => U[]

    Finally returns array containing elements mapped using transformer to provide the new value.

      • (array: T[]): U[]
      • Parameters

        • array: T[]

          Array to map.

        Returns U[]

Const prepend

  • prepend(element: any): <T>(array: T[]) => any[]
  • Finally returns array with element prepended.

    memberof

    core

    since

    0.1.0

    alias

    queue

    alias

    unshift

    see

    push

    example
    prepend(1)([]); //=> [1]
    prepend(4)([1, 2, 3]); //=> [4, 1, 2, 3]
    

    Parameters

    • element: any

      Element to prepend.

    Returns <T>(array: T[]) => any[]

      • <T>(array: T[]): any[]
      • Type parameters

        • T

        Parameters

        • array: T[]

          Array to prepend to.

        Returns any[]

Const push

  • push(element: any): <T>(array: T[]) => any[]
  • Finally returns array with element appended.

    memberof

    core

    since

    0.1.0

    alias

    append

    see

    prepend

    example
    push(1)([]); //=> [1]
    push(4)([1, 2, 3]); //=> [1, 2, 3, 4]
    

    Parameters

    • element: any

      Element to append.

    Returns <T>(array: T[]) => any[]

      • <T>(array: T[]): any[]
      • Type parameters

        • T

        Parameters

        • array: T[]

          Array to append to.

        Returns any[]

Const range

  • range(end: number, options?: RangeOptions): number[]
  • Returns a number array containing numbers generated from RangeOptions.start (inclusive, defaults to 0) to end (both inclusive) where the interval between numbers will be equal to RangeOptions.step (defaults to 1).

    range has standard behaviour except in the special case where the only provided argument is a negative end that is less than start, which conveniently allows decrementing from start to end.

    Examples:

    example
    // Positive ranges:
    range(0); //=> [0] (since `end === start`)
    range(4); //=> [0, 1, 2, 3, 4]
    range(4, { start: 1 }); //=> [1, 2, 3, 4]
    range(10, { step: 2 }); //=> [0, 2, 4, 6, 8, 10]
    
    // Negative ranges:
    range(-4, { step: -1 }); //=> [0, -1, -2, -3, -4] (equivalent to ``)
    range(-4, { step: -2 }); //=> [0, -2, -4]
    
    // Special cases:
    range(-4); //=> [0, -1, -2, -3, -4] (equivalent to `range(-4, { step: -1 })`)
    
    // Error cases:
    range(1, { step: 0 }); //=> TypeError (since prevents range)
    range(-1, { start: 1, step: 2 }); //=> TypeError (since `step` is inverse to `end`)
    range(-1, { start: 1, step: -1 }); //=> TypeError (since `step` is inverse to `end`)
    
    throws

    {TypeError} step cannot be 0.

    throws

    {TypeError} end cannot be less than start when step is positive.

    throws

    {TypeError} end cannot be greater than start whenstep is negative.

    memberof

    core

    since

    0.1.0

    Parameters

    • end: number

      Number to generate up to (inclusive).

    • options: RangeOptions = {}

    Returns number[]

    An array containing numbers generated between start to end (both inclusive) where all numbers are seperated by an inteveral equal to step.

Const reduce

  • reduce(initialValue: any, transformer: (prevValue: any, value: any) => any): <T>(array: T[]) => any
  • Finally returns array reduced to a single value using initialValue as the starting value and transformer to provide the next value.

    memberof

    core

    since

    0.1.0

    see

    filter map promiseReduce reduceEntries

    example
    reduce(0, (prev, v) => prev + v)([]) //=> 0
    reduce(0, (prev, v) => prev + v)([1, 2, 3]) //=> 6
    reduce('', (prev, v) => prev + v)([1, 'a', 'b']) //=> '1ab'
    

    Parameters

    • initialValue: any

      Starting value (i.e., the first prevValue accepted by transformer).

    • transformer: (prevValue: any, value: any) => any

      Accepts prevValue and returns a new prevValue.

        • (prevValue: any, value: any): any
        • Parameters

          • prevValue: any
          • value: any

          Returns any

    Returns <T>(array: T[]) => any

    Finally returns array reduced to a single value.

      • <T>(array: T[]): any
      • Type parameters

        • T

        Parameters

        • array: T[]

          The array with elements to reduce.

        Returns any

Const reverse

  • reverse<T>(array: T[]): T[]
  • Returns array with all elements in reverse order.

    memberof

    core

    since

    0.1.0

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

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to reverse.

    Returns T[]

    Returns array with all elements in reverse order.

Const skip

  • skip(total?: number): <T>(array: T[]) => T[]
  • Finally returns an array containing elements after total elements.

    Returns an unchanged array if total is negative.

    memberof

    core

    since

    0.1.0

    see

    take

    example
     skip()([]); //=> []
     skip(1)([]); //=> []
     skip(1)([1, 2, 3]); //=> [2, 3]
     skip(2)([1, 2, 3]); //=> [3]
     skip(1)([1, 'a', 2]); //=> ['a', 3]
     skip(-1)([1, 2, 3]); //=> [1, 2, 3]
     skip(4)([1, 2, 3]); //=> []
    

    Parameters

    • total: number = 0

      number of elements to skip (optional, defaults to 0).

    Returns <T>(array: T[]) => T[]

    Finally returns an array containing elements after total elements.

      • <T>(array: T[]): T[]
      • Type parameters

        • T

        Parameters

        • array: T[]

          Array with elements to skip.

        Returns T[]

Const slice

  • slice(start?: number, end?: number): <T>(array: T[]) => T[]
  • Finally returns array containing the elements from indexes start to end.

    Returns an unchanged array will be unchanged if start is negative or end is less than start or end exceeds the last index.

    memberof

    core

    since

    0.1.0

    example
    slice()([]) //=> []
    slice(0, 2)([1, 2, 3]) //=> [1, 2, 3]
    slice(0, 1)([1, 2, 3]) //=> [1, 2]
    slice(1, 2)([1, 'a', 2]) //=> ['a', 2]
    

    Parameters

    • start: number = 0

      Index to stop at (inclusive, defaults to last index).

    • Optional end: number

    Returns <T>(array: T[]) => T[]

    Finally returns array containing the elements from indexes start to end.

      • <T>(array: T[]): T[]
      • Type parameters

        • T

        Parameters

        • array: T[]

        Returns T[]

Const tail

  • tail<T>(array: T[]): T[]
  • Returns array without the first element.

    alias

    dequeue

    memberof

    core

    since

    0.1.0

    see

    init last head

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

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to use.

    Returns T[]

    array without the first element.

Const take

  • take(total?: number): <T>(array: T[]) => T[]
  • Finally returns array containing elements before total (inclusive, defaults to 0) elements.

    Returns an empty array if total is negative.

    memberof

    core

    since

    0.1.0

    see

    skip slice takeLast takePart

    example
    take()([]); //=> []
    take(1)([]); //=> []
    take(1)([1]); //=> [1]
    take(2)([1, 2]); //=> [1, 2]
    take(1)([1]); //=> [1]
    take(-1)([]); //=> []
    take(4)([1, 2, 3]); //=> [1, 2, 3]
    

    Parameters

    • total: number = 0

      number of elements to take (inclusive, defaults to 0).

    Returns <T>(array: T[]) => T[]

    Finally returns array containing elements before total elements.

      • <T>(array: T[]): T[]
      • Type parameters

        • T

        Parameters

        • array: T[]

          Array to use.

        Returns T[]

Const takeLast

  • takeLast(total?: number): <T>(array: T[]) => T[]
  • A reversed alternative to take, i.e., finally returns an array containing a total number of elements taken from the end of array.

    Returns an empty array if total is negative.

    memberof

    core

    since

    0.1.0

    see

    reverse skip take

    example
     takeLast()([]); //=> []
     takeLast(1)([]); //=> []
     takeLast(1)([1]); //=> [1]
     takeLast(2)([1, 2, 3]); //=> [3, 2]
     takeLast(1)([1]); //=> [1]
     takeLast(-1)([]); //=> []
     takeLast(4)([1, 2, 3]); //=> [3, 2, 1]
    

    Parameters

    • total: number = 0

      Number of elements to take (inclusive, defaults to 0).

    Returns <T>(array: T[]) => T[]

    Finally returns an array containing a total number of elements taken from the end of array.

      • <T>(array: T[]): T[]
      • Type parameters

        • T

        Parameters

        • array: T[]

          Array to use.

        Returns T[]

Const takePart

  • takePart(total?: number): <T>(array: T[]) => T[][]
  • Combines take & skip to finally return a 2D array where the first array contains the taken elements (i.e., before and including the total'th element) whilst the second array contains the remaining untaken elements (i.e., [[...taken], [...untaken]]).

    Returns an empty 2D array (i.e., [[], []]) if total is negative.

    memberof

    core

    since

    0.1.0

    see

    filterPart take skip

    example
     takePart()([]); //=> [[], []]
     takePart(1)([]); //=> [[], []]
     takePart(1)([1]); //=> [[1], []]
     takePart(2)([1, 2, 3]); //=> [[1, 2], [3]]
     takePart(1)([1]); //=> [[1], []]
     takePart(-1)([]); //=> [[], []]
     takePart(4)([1, 2, 3]); //=> [[1, 2, 3], []]
    

    Parameters

    • total: number = 0

      The number elements to take (optional, defaults to 0).

    Returns <T>(array: T[]) => T[][]

    Finally returns an array containing 2 arrays of the form [...taken, ...untaken], or an empty 2D array if total is negative.

      • <T>(array: T[]): T[][]
      • Type parameters

        • T

        Parameters

        • array: T[]

          Array to use.

        Returns T[][]

Const union

  • union<T>(array1: T[]): <U>(array2: U[]) => (T | U)[]
  • Finally returns an array set (i.e., array without duplicates) containing all elements from array1 & array2.

    memberof

    core

    since

    0.1.0

    see

    concat uniq

    example
    union([])([]) //=> []
    union([])([1, 2, 3]) //=> [1, 2, 3]
    union([1])([1]) //=> [1]
    union([1, 2])([1, 2]) //=> [1, 2]
    union([1, 2])([3, 4]) //=> [1, 2, 3, 4]
    union([1, 'a'])([1, 'b']) //=> [1, 'a', 'b']
    

    Type parameters

    • T

    Parameters

    • array1: T[]

      First array to use.

    Returns <U>(array2: U[]) => (T | U)[]

    Finally returns an array set containing all unique elements from array1 & array2.

      • <U>(array2: U[]): (T | U)[]
      • Type parameters

        • U

        Parameters

        • array2: U[]

          second array to use.

        Returns (T | U)[]

Const uniq

  • uniq<T>(array: T[]): T[]
  • Returns array without duplicate primitive elements (i.e., reference elements such as arrays & object elements are not tested hence are considered unique).

    memberof

    core

    since

    0.1.0

    example
     uniq([]); //=> []
     uniq([1, 1, 'a', 'a']); //=> [1, 2]
     uniq([[], [], {}, {}]); //=> [[], [], {}, {}]
    

    Type parameters

    • T

    Parameters

    • array: T[]

      Array to use.

    Returns T[]

    Returns array without duplicate primitive elements

Boolean Functions

Const isBoolean

  • isBoolean(value: any): boolean
  • Returns true if value is a boolean, else returns false.

    memberof

    core

    since

    0.1.0

    example
    // Boolean values.
    isBoolean(true); //=>  true
    isBoolean(false); //=>  true
    
    // Non-boolean values.
    isBoolean(undefined); //=>  false
    isBoolean(null); //=>  false
    isBoolean(1); //=>  false
    isBoolean('a'); //=>  false
    isBoolean([1]); //=>  false
    isBoolean({ a: 1 }); //=>  false
    

    Parameters

    • value: any

      Value to test.

    Returns boolean

    true if value is a boolean, else returns false.

Function Functions

Const also

  • also<T>(value: T, handler: (it: T) => T): T
  • Runs handler, which receives a contextual object it representing value, before returning value.

    Useful for running statements before assigning the resulting object to a variable:

    example
    const numbers = [1, 2];
    const threeNumbers = also(numbers, it => {
      console.log(it); // Prints `[1, 2]`
      it.append(3);
      console.log(it); // Prints `[1, 2, 3]`
      return it;
    });
    threeNumbers; //=> [1, 2, 3]
    
    memberof

    core

    since

    1.0.0

    example
    also() //=> Error
    also('foo', it => {
     it = `${it} bar`
     return it;
    }); //=> 'foo bar'
    

    Type parameters

    • T

    Parameters

    • value: T
    • handler: (it: T) => T
        • (it: T): T
        • Parameters

          • it: T

          Returns T

    Returns T

    Returns value.

Const compose

  • compose<Functions>(...functions: Functions): (initialValue?: any) => LastReturnType
  • Sequentially applies functions in a mathematical right-to-left order with a beginning value of initialValue to finally return the output of the first (i.e., left-most) function in functions.

    Useful for composing a series of functions on an initial value where the output of a function is passed as an argument to the next function until a final result is returned by the final function (N.B., the first function in functions is the final function since compose uses mathematical right-to-left composition):

    example
    // Composing on number.
    const isEven = n => n % 2 === 0;
    const double = n => n * 2;
    const isDoubledNumberEven = compose(isEven, double);
    isDoubledNumberEven(1) //=> true
    
    Composing on numbers.
    const keepEvenNumbers = numbers => numbers.filter(isEven)
    const doubleNumbers = numbers => numbers.map(double)
    const doubleEvenNumbers = compose(doubleNumbers, keepEvenNumbers);
    doubleEvenNumbers([1, 2, 3]); // [4]
    
    memberof

    core

    since

    0.1.0

    see

    pipe

    example
    const isEven = n => n % 2 === 0;
    const double = n => n * 2;
    const doubleNumbers = numbers => numbers.map(double);
    
    compose()() //=> undefined
    compose(isEven)(1) //=> false
    compose(isEven, double)(1) //=> true
    compose(doubleNumbers)([1, 2, 3]) //=> [2, 4, 6]
    

    Type parameters

    • Functions: AnyFunction[]

    Parameters

    • Rest ...functions: Functions

      Unary functions to compose (optional, defaults to []).

    Returns (initialValue?: any) => LastReturnType

    Finally returns the output of the first (i.e., left-most) function in functions.

      • (initialValue?: any): LastReturnType
      • Parameters

        • Optional initialValue: any

          The initial value that is passed to the first function in functions (optional, defaults to undefined).

        Returns LastReturnType

Const contra

  • contra(..._: any[]): boolean
  • Always returns false regardless of passed arguments.

    Useful for defaulting an anonymous function to false:

    example
    // Default `predicate` function to always return `false` hence `filterNumbers` defaults to
    remove all elements if no `predicate`.
    const filterNumbers = (array = [], predicate = contra) => array.filter(predicate);
    const numbers = [1, 2, 3];
    const isEven = n => n % 2 === 0;
    filterNumbers(numbers, isEven); //=> [2]
    // Defaulted to no elements via `contra`:
    filterNumbers(numbers); //=> []
    
    memberof

    core

    since

    0.1.0

    see

    tauto

    example
    contra() //=> false
    contra('foo', 'bar') //=> false
    

    Parameters

    • Rest ..._: any[]

    Returns boolean

    false regardless of passed arguments.

Const ifElse

  • ifElse<TValue, TFinal>(predicate?: (value?: TValue) => boolean, onTrue?: (value?: TValue) => TFinal, onFalse?: (value?: TValue) => TFinal): (value?: TValue) => TFinal
  • Finally returns onTrue's output if predicate returns true, else returns onFalse's output.

    Useful when conditionally returning a new value based on a condition:

    example
    const firstElement = array => array[0];
    const isEven = n % 2 === 0;
    const onEven = () => 'even';
    const onOdd = () => 'odd';
    
    const firstNumberEvenString = compose(ifElse(isEven, onEven, onOdd), firstElement);
    firstNumberEvenString([1, 2, 3]) //=> 'odd'
    firstNumberEvenString([2, 3]) //=> 'even'
    
    
    memberof

    core

    since

    0.1.0

    see

    tryOr

    example
    const isEven = n => n % 2 === 0;
    const onEven = () => 'even';
    const onOdd = () => 'odd';
    
    ifElse()(); //=> undefined (via `onFalse`)
    ifElse()(2); //=> undefined (via `onFalse`)
    ifElse(isEven)(2); //=> undefined (via `onTrue`)
    ifElse(isEven, onEven)(2); //=> 'even'
    ifElse(isEven, onEven, onOdd)(2) //=> 'even'
    ifElse(isEven, onEven, onOdd)(1) //=> 'odd'
    

    Type parameters

    • TValue

    • TFinal

    Parameters

    • predicate: (value?: TValue) => boolean = ...

      Returns a boolean based on value where true triggers onTrue & false triggers onFalse, (optional, defaults to return false). optional value (optional, defaults to return value).

        • (value?: TValue): boolean
        • Parameters

          • Optional value: TValue

          Returns boolean

    • onTrue: (value?: TValue) => TFinal = ...

      Returns the new value if predicate returns true (optional, defaults to return undefined).

        • (value?: TValue): TFinal
        • Parameters

          • Optional value: TValue

          Returns TFinal

    • onFalse: (value?: TValue) => TFinal = ...

      Returns the new value if predicate returns false (optional, defaults to return undefined). tryer (optional, defaults to return value). optional value (optional, defaults to return value).

        • (value?: TValue): TFinal
        • Parameters

          • Optional value: TValue

          Returns TFinal

    Returns (value?: TValue) => TFinal

    Finally returns output of tryer if no errors are thrown, else returns the output of defaulter.

      • (value?: TValue): TFinal
      • Parameters

        • Optional value: TValue

          The value to test via predicate.

        Returns TFinal

Const isFunction

  • isFunction(value?: any): boolean
  • Returns true if value is a function (via typeof), else return `false.

    memberof

    core

    since

    0.1.0

    example
    // Function values.
    isFunction(() => undefined) //=> true
    
    // Non-function values.
    isFunction() //=> false
    isFunction(undefined) //=> false
    isFunction(true) //=> false
    isFunction(1) //=> false
    isFunction('foo') //=> false
    isFunction(null) //=> false
    isFunction({ a: 1, b: 2, c: 3 }) //=> false
    isFunction([1, 2, 3]) //=> false
    

    Parameters

    • Optional value: any

      Value to check.

    Returns boolean

    true if value is a function (via typeof), else return `false

Const isPromise

  • isPromise(value?: any): boolean
  • Returns true if value is an instance of Promise, else returns false.

    memberof

    core

    since

    0.1.0

    see

    isFunction

    example
    // Promises values.
    isPromise(Promise.resolve(1)) //=> true
    isPromise(Promise.reject(1)) //=> true
    isPromise(new Promise(() => undefined)) //=> true
    isPromise(new Promise(r => r(1))) //=> true
    isPromise(new Promise(r => r(1))) //=> true
    
    // Non-promises values.
    isPromise() //=> false
    isPromise(undefined) //=> false
    isPromise(true) //=> false
    isPromise(1) //=> false
    isPromise('foo') //=> false
    isPromise(() => undefined) //=> false
    isPromise(() => Promise.resolve(1)) //=> false
    isPromise(async () => 1) //=> false
    isPromise(async () => await 1) //=> false
    isPromise(null) //=> false
    isPromise({ a: 1, b: 2, c: 3 }) //=> false
    isPromise([1, 2, 3]) //=> false
    

    Parameters

    • Optional value: any

      Value to check.

    Returns boolean

    true if value is a Promise, else returns false.

Const negate

  • negate(predicate?: (...args: any[]) => boolean): (...args: any[]) => boolean
  • Finally returns the inverted boolean returned by predicate.

    Useful for inverting predicate functions:

    example
    // Negating 1 argument `predicate`.
    const isEven = n => n % 2 === 0; // Original predicate.
    isEven(2); //=> true
    const isOdd = negate(isEven); // Negated predicate.
    isOdd(2); //=> false
    
    // Negating 2 argument `predicate`.
    const isEvenArgs = (...args) => args.length % 2 === 0;
    isEvenArgs('foo', 'bar') // true
    const isOddArgs = negate(isEvenArgs);
    isOddArgs('foo', 'bar'); //=> false
    
    memberof

    core

    since

    0.1.0

    see

    contra logicalNot tauto

    example
    negate() //=> false
    negate(() => true) //=> false
    negate(() => false) //=> true
    const isEvenArgs = (...args) => args.length % 2 === 0;
    isEvenArgs('foo', 'bar') // true
    negate(isEvenArgs)('foo', bar'); //=> false
    

    Parameters

    • predicate: (...args: any[]) => boolean = ...

      Non-curried function that returns a boolean to negate (optional, defaults to return true)

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

          • Rest ...args: any[]

          Returns boolean

    Returns (...args: any[]) => boolean

    Finally returns the inverted boolean returned by predicate.

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

        • Rest ...args: any[]

        Returns boolean

Const noop

  • noop(..._: any[]): undefined
  • Always returns undefined regardless of passed arguments.

    Useful for providing a function as a placeholder without side effects:

    example
    // ...
    if (disabled) button.onClick = noop; // `noop` is called on click but no operation is performed.
    
    memberof

    core

    since

    0.1.0

    example
    noop() //=> undefined
    noop('foo', 'bar') //=> undefined
    

    Parameters

    • Rest ..._: any[]

    Returns undefined

    undefined regardless of passed arguments.

Const opRuntime

  • opRuntime(testFunction: AnyFunction): Promise<number>
  • Returns a Promise that resolves to the time in milliseconds for testFunction to return.

    memberof

    core

    since

    0.1.0

    see

    delayFor

    example
    const runtimeMs = 2000;
    const longRunningOperation = async () => await new Promise(r => setTimeout(r, runtimeMs);
    
    opRuntime(longRunningOperation); //=> t where t >= runtimeMs
    

    Parameters

    • testFunction: AnyFunction

      function to test.

    Returns Promise<number>

    A Promise that resolves to the time in milliseconds for testFunction to return.

Const pipe

  • pipe<Functions>(...functions: Functions): (initialValue?: any) => LastReturnType
  • Identical to compose but reverses the order of functions, i.e., sequentially applies functions in a computational left-to-right order with a beginning value of initialValue.

    memberof

    core

    since

    0.1.0

    example
    const isEven = n => n % 2 === 0;
    const double = n => n * 2;
    const doubleNumbers = numbers => numbers.map(double);
    
    pipe()() //=> undefined
    pipe(isEven)(1) //=> false
    pipe(double, isEven)(1) //=> true
    pipe(doubleNumbers)([1, 2, 3]) //=> [2, 4, 6]
    

    Type parameters

    • Functions: AnyFunction[]

    Parameters

    • Rest ...functions: Functions

      Unary functions to pipe (optional, defaults to []).

    Returns (initialValue?: any) => LastReturnType

    Finally returns the output of the first (i.e., right-most) function in functions.

      • (initialValue?: any): LastReturnType
      • Parameters

        • Optional initialValue: any

          The initial value that is passed to the first function in functions (optional, defaults to undefined).

        Returns LastReturnType

Const promiseLog

  • promiseLog(message: string, loggerFunction?: LoggerFunction): <T>(promise: Promise<T>) => Promise<any>
  • Convenient alternative to using tapLog with Promises. I.e., passes message & resolved promise value to loggerFunction to allow logging before finally returning the unchanged promise.

    Useful for logging a Promise value before returning it unchanged for further use with other promise functions (e.g., during composition):

    example
    const fetchUsers = () => {
        // ...returns Promise<any[]>.
    };
    const firstElement = array = array[0];
    const logThenReturnFirstUser = () => compose(firstElement, promiseLog)(fetchUsers());
    logThenReturnFirstUser(); //=> (logs users then returns first user)
    
    memberof

    core

    since

    0.1.0

    see

    tapLog

    example
    promiseLog('foo')(Promise.resolve(1)) //=> (logs `foo` & `1` then returns `Promise`)
    

    Parameters

    • message: string

      Message passed to loggerFunction.

    • loggerFunction: LoggerFunction = ...

      LoggerFunction to pass message and resolved promise to (optional, defaults to console.debug, has no effect on the finally returned value).

    Returns <T>(promise: Promise<T>) => Promise<any>

    Finally returns the unchanged promise.

      • <T>(promise: Promise<T>): Promise<any>
      • Type parameters

        • T

        Parameters

        • promise: Promise<T>

          The Promise to log.

        Returns Promise<any>

Const promiseTryOr

  • promiseTryOr<TValue, TFinal>(tryer?: (value?: TValue) => Promise<TFinal>, defaulter?: (value?: TValue, error?: unknown) => TFinal): (value?: TValue) => Promise<TFinal>
  • Asynchronous alternative to tryOr. I.e., finally returns output of tryer if no errors are thrown, else returns the output of defaulter.

    Useful for trying potentially errorful asynchronous operations and returning the successful output or defaulting an errorful output to a specific value:

    example
    // Errorful asynchronous function.
    const getFileContents = (filePath) => new Promise((__, reject) => setTimeout(
        () => reject('error'), 100
    ));
    const defaultFileContents = (value, error) => {
        // ...optionally handle error.
        return 'foo'; // Provide default value.
    };
    const fileContentsOrDefault = promiseTryOr(getFileContents, defaultFileContents);
    const nonExistantFilePath = undefined;
    // Errorful output caught and defaulted.
    await fileContentsOrDefault(nonExistantFilePath); //=> 'foo'
    
    memberof

    core

    since

    0.1.0

    see

    tryOr

    Type parameters

    • TValue

    • TFinal

    Parameters

    • tryer: (value?: TValue) => Promise<TFinal> = ...

      Asynchronous function (accepting value) that is tried to return a final value if no errors occur.

        • (value?: TValue): Promise<TFinal>
        • Parameters

          • Optional value: TValue

          Returns Promise<TFinal>

    • defaulter: (value?: TValue, error?: unknown) => TFinal = ...

      See tryOr

        • (value?: TValue, error?: unknown): TFinal
        • Parameters

          • Optional value: TValue
          • Optional error: unknown

          Returns TFinal

    Returns (value?: TValue) => Promise<TFinal>

    Finally returns a Promise containing that resolves to the output of tryer if no errors are thrown, else resolves to the output of defaulter.

      • (value?: TValue): Promise<TFinal>
      • Parameters

        • Optional value: TValue

          See tryOr

        Returns Promise<TFinal>

Const runNow

  • runNow(functionToRun: AnyFunction): any
  • Immediately runs functionToRun and returns its output.

    Serves as a convenient alternative to using an IFFE (Immediately invoked function expression) whilst reducing the number of parantheses to achieve the same behaviour.

    Useful for immediatley running a function:

    example
    // Immediately run `main` function:
    const main = () => {
        // ...
    };
    runNow(main);
    
    // Immediately initialise variable via function:
    const getEnvironment = (defaultValue) => {
        try {
             throw new Error('Not found'); // Assuming runtime value fails.
        } catch (e: unknown) {
            return defaultValue;
        }
    };
    const environment = runNow(() => getEnvironment('development')); // Initialise variable.
    environment; //=> 'development'
    
    memberof

    core

    since

    0.1.0

    example
    runNow() //=> undefined
    runNow(() => double(1)) //=> 2
    

    Parameters

    • functionToRun: AnyFunction

      Function to run (optional, defaults to return undefined).

    Returns any

    Output from functionToRun.

Const runStringTypeValues

  • runStringTypeValues(valueMapper: (testValue: any, stringTypeName: StringType) => any): Record<string, Record<string, any>>
  • Returns AllStringTypeExampleValues with the values of all StringTypeExampleValues updated using valueMapper.

    Useful for testing a function on all possible string type values based on StringTypeDetails.

    example
    // Expect `stringTypeIs` to return `true` when given correct `stringTypeName` and value:
    
    // E.g., `expected = { boolean: { true: v, ... }, ... };` where `v` was updated to `true`.
    const expected = runStringTypeValues(() => true);
    
    // Run `stringTypeIs` on all string type values:
    
    const results = runStringTypeValues(
    // E.g., `expected = { boolean: { true: v, ... }, ... };` where `v` was updated to the output of `stringTypeIs`.
        (testValue, stringTypeName) => stringTypeIs(stringTypeName)(testValue)
    );
    
    // Compare expectations, e.g.:
    expect(results).toStrictEqual(expected);
    
    memberof

    core

    since

    0.1.0

    see

    runTestCases

    Parameters

    • valueMapper: (testValue: any, stringTypeName: StringType) => any

      Returns a new value for each StringTypeExampleValues.

        • (testValue: any, stringTypeName: StringType): any
        • Parameters

          • testValue: any
          • stringTypeName: StringType

          Returns any

    Returns Record<string, Record<string, any>>

    AllStringTypeExampleValues with the values of all StringTypeExampleValues updated using valueMapper.

Const runTestCases

  • runTestCases(testFunction: AnyFunction, testCases?: TestCases): TestCases
  • Finally returns testCases where TestCaseDetail.expectedResult in all entries are updated using testFunction.

    Each ArgSet in TestCaseDetail.argSets will be passed to successive calls of testFunction to support curried functions:

    example
    const addNumbers = (a: number) => (b: number) => a + b; // Curried `testFunction`.
    const expectedTestCases: TestCases = {
        'adds numbers': {
            argSets: [ // Arguments for each call of `testFunction`.
                [1], // Arguments passed to 1st call of `testFunction`, i.e., `addNumbers(1)`.
                [2], // I.e.: `addNumbers(1)(2)`.
            ],
            expectedResult: 3,
        },
        // ...
    };
    
    const resultTestCases = runTestCases(addNumbers, expectedTestCases);
    

    Useful for collecting a function's output for several test values in an updated TestCase object that can be logged or compared against the original TestCase object:

    example
    // Setup using 1 argument for a non-curried `testFunction`:
    const doubleNumber = (n: number) => n * 2;
    const expectedTestCases: TestCases = {
        'doubles negative': {
            argSets: [[-1]],
            expectedResult: -2,
        },
        'doubles number': {
            testValue: [[1]],
            expectedResult: 2,
        },
    };
    
    // Results:
    const doubleNumberResults = runTestCases(doubleNumber, expectedTestCaseData);
    
    // Inspection:
    console.log(doubleNumberResults);
    // Compare expected results to test case results, e.g.:
    expect(doubleNumberResults).toStrictEqual(expectedTestCaseData);
    
    memberof

    core

    since

    0.1.0

    Parameters

    • testFunction: AnyFunction

      Function to test via updating test cases.

    • testCases: TestCases = {}

      TestCases to run.

    Returns TestCases

    Finally returns testCases where TestCaseDetail.expectedResult in all entries are updated using testFunction.

Const tap

  • tap<T, U>(transformer: (value: T) => U): (value: T) => U
  • Uses transformer to finally return a new value for value.

    memberof

    core

    since

    0.1.0

    example
    tap(v => v * 2)(2) //=> 4
    

    Type parameters

    • T

    • U

    Parameters

    • transformer: (value: T) => U

      Returns a new value.

        • (value: T): U
        • Parameters

          • value: T

          Returns U

    Returns (value: T) => U

    Finally returns a new value.

      • (value: T): U
      • Parameters

        • value: T

          Value to test.

        Returns U

Const tapLog

  • tapLog(message: string, loggerFunction?: LoggerFunction): (...args: any[]) => any
  • Passes message and args to a loggerFunction that is run before finally returning the first argument in args.

    Serves as a convenient and extended alternative to passing a logger function to tap to log an argument for inspection before returning it for further usage.

    memberof

    core

    since

    0.1.0

    see

    promiseLog tap

    example
    // Using default logger.
    tapLog('foo')() //=> undefined
    tapLog('foo')('bar') //=> 'bar'
    tapLog('foo')('bar', 'baz') //=> 'bar'
    
    // Using custom logger.
    const errorLogger: LoggerFunction  = (message, ...args) => console.error(message);
    tapLog('foo', errorLogger)('bar') //=> 'bar' (logs `foo` via `console.error`)
    

    Parameters

    • message: string

      Message passed to loggerFunction.

    • loggerFunction: LoggerFunction = ...

      LoggerFunction to pass message and args to (optional, defaults to console.debug, has no effect on the finally returned value).

    Returns (...args: any[]) => any

    Finally returns the first argument in args.

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

        • Rest ...args: any[]

          All arguments to log where the first argument is finally returned.

        Returns any

Const tauto

  • tauto(..._: any[]): boolean
  • Always returns true regardless of passes arguments.

    Useful for defaulting an anonymous function to false:

    example
    // Default `predicate` function to always return `true` hence `filterNumbers` defaults to
    keep all elements if no `predicate`.
    const filterNumbers = (array = [], predicate = tauto) => array.filter(predicate);
    const numbers = [1, 2, 3];
    const isEven = n => n % 2 === 0;
    filterNumbers(numbers, isEven); //=> [2]
    // Defaulted to keep elements via `tauto`:
    filterNumbers(numbers); //=> [1, 2, 3]
    
    memberof

    core

    since

    0.1.0

    see

    identity contra

    example
    tauto() //=> true
    tauto('foo', 'bar') //=> true
    

    Parameters

    • Rest ..._: any[]

    Returns boolean

    true regardless of passes arguments.

Const throwIf

  • throwIf<TValue>(predicate?: (value: TValue) => boolean, error?: Error): (value: TValue) => TValue
  • Finally returns value if predicate returns false, else throws error.

    Useful for halting an invalid composition:

    example
    const isOdd = n => n % 2 !== 0;
    const double = n => n * 2;
    const doubleEvenNumber = compose(double, throwIf(isOdd, 'Number must be even'))
    doubleEvenNumber(2); //=> 4
    doubleEvenNumber(1) //=> Error('Number must be even')
    
    throws

    {Error} Throws error.

    memberof

    core

    since

    0.1.0

    see

    tap tryOr

    example
    const isOdd = n => n % 2 !== 0;
    
    throwIf(isOdd)(2) //=> 2
    throwIf(isOdd)(1) //=> Error('throwIf: Predicate is true for << 1 >>')
    throwIf(isOdd, new TypeError('Number must be even'))(1) //=> TypeError('Number must be even')
    

    Type parameters

    • TValue

    Parameters

    • predicate: (value: TValue) => boolean = ...

      Returns true to throw error (optional, defaults to return true), or returns false to return value.

        • (value: TValue): boolean
        • Parameters

          • value: TValue

          Returns boolean

    • error: Error = ...

      Error to throw (optional, defaults to a generic error).

    Returns (value: TValue) => TValue

    Finally returns value is predicate is false, else throws.

      • (value: TValue): TValue
      • Parameters

        • value: TValue

          Value to test.

        Returns TValue

Const tryOr

  • tryOr<TValue, TFinal>(tryer?: (value?: TValue) => TFinal, defaulter?: (value?: TValue, error?: unknown) => TFinal): (value?: TValue) => TFinal
  • Finally returns output of tryer if no errors are thrown, else returns the output of defaulter.

    Useful for trying potentially errorful operations and returning the successful output or defaulting an errorful output to a specific value:

    example
    const getFileContents = (filePath) => { // Errorful function.
        // ...
    };
    const defaultFileContents = (value, error) => {
        // ...optionally handle error.
        return 'foo'; // Provide default value.
    };
    const fileContentsOrDefault = tryOr(getFileContents, defaultFileContents);
    const nonExistantFilePath = undefined;
    fileContentsOrDefault(nonExistantFilePath); //=> 'foo' // Errorful output caught and defaulted.
    
    memberof

    core

    since

    0.1.0

    see

    throwIf promiseTryOr

    example
    const trySafe = v => v;
    const tryUnsafe = () => {
        thow new Error();
    };
    const defaultFoo = () => 'foo';
    
    tryOr()() //=> undefined (via `tryer`)
    tryOr(undefined, defaultFoo)(2) //=> 2 (via `tryer`)
    tryOr(trySafe)(2) //=> 2
    tryOr(tryUnsafe)(2) //=> 2 (via `defaulter`)
    tryOr(tryUnsafe, defaultFoo)(2) //=> 'foo'
    

    Type parameters

    • TValue

    • TFinal

    Parameters

    • tryer: (value?: TValue) => TFinal = ...

      Tries to return a new value based on optional value (optional, defaults to return value).

        • (value?: TValue): TFinal
        • Parameters

          • Optional value: TValue

          Returns TFinal

    • defaulter: (value?: TValue, error?: unknown) => TFinal = ...

      Returns the default value if an error occurs in tryer (optional, defaults to return value). optional value (optional, defaults to return value).

        • (value?: TValue, error?: unknown): TFinal
        • Parameters

          • Optional value: TValue
          • Optional error: unknown

          Returns TFinal

    Returns (value?: TValue) => TFinal

    Finally returns output of tryer if no errors are thrown, else returns the output of defaulter.

      • (value?: TValue): TFinal
      • Parameters

        • Optional value: TValue

          The value to try a potentially errorful operation on.

        Returns TFinal

Logic Functions

Const assertStrictEquals

  • assertStrictEquals(value1?: any, errorMessage?: string): (value2?: any) => void
  • Convenience function similar to strictEquals but throws an error if value1 is strictly equal (via ===) to value2, else returns void.

    throws

    {TypeError} value must be a hex string.

    memberof

    core

    since

    1.0.0

    example
    assertStrictEquals()() //=> undefined
    assertStrictEquals()(1) //=> Error
    assertStrictEquals(1)() //=> Error
    assertStrictEquals(1)(1) //=> undefined
    assertStrictEquals(1)(2) //=> Error
    
    // Config.
    assertStrictEquals(1, 'foo bar')(2) //=> Error where message includes 'foo bar'
    
    // Objects (similar for arrays, functions, & symbols).
    assertStrictEquals({ a: 1 })({ a: 1 }) //=> Error
    const myObject = { a: 1 }
    assertStrictEquals(myObject)(myObject) //=> undefined
    

    Parameters

    • Optional value1: any

      First value to compare.

    • Optional errorMessage: string

      Optional message to include in thrown error.

    Returns (value2?: any) => void

    Finally returns true if value1 is strictly equal (via ===) to value2, else returns false.

      • (value2?: any): void
      • Parameters

        • Optional value2: any

          Second value to compare.

        Returns void

Const getStringType

  • getStringType(value?: any): "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"
  • Returns a string (via typeof) indicating the type of value.

    memberof

    core

    since

    0.1.0

    see

    stringTypeIs

    example
    getStringType() //=> 'undefined'
    getStringType(undefined) //=> 'undefined'
    getStringType(true) //=> 'boolean'
    getStringType(1) //=> 'number'
    getStringType('foo') //=> 'string'
    getStringType({ a: 1, b: 2, c: 3 }) //=> 'object'
    getStringType(null) //=> 'object'
    

    Parameters

    • Optional value: any

      The value to check.

    Returns "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"

    String indicating the type of value.

Const identity

  • identity<T>(identityValue: T, ..._: any[]): T
  • Always returns the identityValue (i.e., the first argument).

    memberof

    core

    since

    0.1.0

    see

    contra noop tauto

    example
    identity(1); // => 1
    identity(1, 2); // => 1
    

    Type parameters

    • T

    Parameters

    • identityValue: T

      Value to return.

    • Rest ..._: any[]

    Returns T

    Always returns the identityValue (i.e., the first argument).

Const isInstanceOf

  • isInstanceOf(expectedInstanceType?: any): (value?: any) => boolean
  • Finally returns true if value is an instance (via instanceof) of expectedInstanceType.

    memberof

    core

    since

    0.1.0

    example
    class User { name = 'foo'; }
    class Admin extends User { settings = 'foo'; }
    
    isInstanceOf()() //=> false
    isInstanceOf()(undefined) //=> false
    isInstanceOf(User)(undefined) //=> false
    isInstanceOf(User)(new User()) //=> true
    isInstanceOf(User)(new Admin()) //=> true
    

    Parameters

    • Optional expectedInstanceType: any

      The expected instance type.

    Returns (value?: any) => boolean

    true if values's string type is equal to expectedStringType

      • (value?: any): boolean
      • Parameters

        • Optional value: any

          The value to check the instance type of.

        Returns boolean

Const isNil

  • isNil(value?: any): boolean
  • Returns true if value is either null or undefined, else returns false.

    memberof

    core

    since

    0.1.0

    example
    // Nil values.
    isNil(undefined) //=> true
    isNil(null) //=> true
    
    // Non-nil values.
    isNil([]) //=> false
    isNil([1, '2', 3]) //=> false
    isNil({}) //=> false
    isNil({ a: 1, b: '2', c: 3 }) //=> false
    isNil('') //=> false
    isNil('foo bar baz') //=> false
    isNil(true) //=> false
    isNil(false) //=> false
    isNil(-1) //=> false
    isNil(0) //=> false
    isNil(1) //=> false
    isNil(1.1) //=> false
    

    Parameters

    • Optional value: any

      Value to test.

    Returns boolean

    true if value is either null or undefined, else returns false.

Const logicalAnd

  • logicalAnd(value1?: boolean): (value2?: boolean) => boolean
  • Finally returns true if both value1 & value2 are true, else returns false.

    memberof

    core

    since

    0.1.0

    example
    logicalAnd()() //=> false
    logicalAnd(true)() //=> false
    logicalAnd()(true) //=> false
    logicalAnd(false)(false) //=> false
    logicalAnd(true)(false) //=> false
    logicalAnd(true)(true) //=> true
    

    Parameters

    • Optional value1: boolean

      First boolean to compare.

    Returns (value2?: boolean) => boolean

    Finally returns true if both value1 & value2 are true, else returns false.

      • (value2?: boolean): boolean
      • Parameters

        • Optional value2: boolean

          Second boolean to compare.

        Returns boolean

Const logicalNot

  • logicalNot(value: boolean): boolean
  • Inverts (via !) boolean value, i.e., returns true if value is false, else returns false.

    memberof

    core

    since

    0.1.0

    example
    logicalNot(false) //=> true
    logicalNot(true) //=> false
    

    Parameters

    • value: boolean

      boolean to invert.

    Returns boolean

    Returns true if value is false, else returns false.

Const logicalOr

  • logicalOr(value1?: boolean): (value2?: boolean) => boolean
  • Finally returns true if either or both value1 & value2 are true, else returns false.

    memberof

    core

    since

    0.1.0

    example
    logicalOr()() //=> false
    logicalOr(true)() //=> true
    logicalOr()(true) //=> true
    logicalOr(false)(false) //=> false
    logicalOr(true)(false) //=> true
    logicalAnd(true)(true) //=> true
    

    Parameters

    • Optional value1: boolean

      First boolean to compare.

    Returns (value2?: boolean) => boolean

    Finally returns true if either or both value1 & value2 are true, else returns false.

      • (value2?: boolean): boolean
      • Parameters

        • Optional value2: boolean

          Second boolean to compare.

        Returns boolean

Const maxCallStackSize

  • maxCallStackSize(): number
  • Returns the max number of calls for the call stack.

    memberof

    core

    since

    0.1.0

    example
    maxCallStackSize() //=> n where n is a positive integer
    

    Returns number

    Max number of calls for the call stack.

Const strictEquals

  • strictEquals(value1?: any): (value2?: any) => boolean
  • Finally returns true if value1 is strictly equal (via ===) to value2, else returns false.

    memberof

    core

    since

    0.1.0

    example
    strictEquals()() //=> true
    strictEquals()(1) //=> false
    strictEquals(1)() //=> false
    strictEquals(1)(1) //=> true
    strictEquals(1)(2) //=> false
    strictEquals(undefined)(undefined) //=> true
    strictEquals(true)(true) //=> true
    strictEquals('foo')('foo') //=> true
    strictEquals({})({}) //=> true
    strictEquals({ a: 1, b: 2, c: 3 })({ a: 1, b: 2, c: 3 }) //=> true
    strictEquals([])([]) //=> true
    strictEquals([1, 2, 3])([1, 2, 3]) //=> true
    

    Parameters

    • Optional value1: any

      First value to compare.

    Returns (value2?: any) => boolean

    Finally returns true if value1 is strictly equal (via ===) to value2, else returns false.

      • (value2?: any): boolean
      • Parameters

        • Optional value2: any

          Second value to compare.

        Returns boolean

Const stringTypeIs

  • stringTypeIs(expectedStringType?: string): (value?: any) => boolean
  • Finally returns true if value's string type (i.e., returned by typeof) is equal to expectedStringType.

    memberof

    core

    since

    0.1.0

    example
    stringTypeIs()() //=> false
    stringTypeIs()(undefined) //=> false
    stringTypeIs('undefined')(null) //=> false
    stringTypeIs('undefined')(undefined) //=> true
    stringTypeIs('boolean')(true) //=> true
    stringTypeIs('number')(1) //=> true
    stringTypeIs('string')('foo') //=> true
    stringTypeIs('object')({ a: 1, b: 2, c: 3 }) //=> true
    stringTypeIs('object')(null) //=> true
    

    Parameters

    • Optional expectedStringType: string

      The expected string type.

    Returns (value?: any) => boolean

    Finally returns true if values's string type is equal to expectedStringType.

      • (value?: any): boolean
      • Parameters

        • Optional value: any

          The value to check the stirng type of.

        Returns boolean

Const valueIf

  • valueIf<T>(predicate: (value: T) => boolean, defaultValue: T): (value: T) => T
  • Finally returns value if predicate returns true, else returns defaultValue.

    memberof

    core

    since

    0.1.0

    see

    arrayIf stringIf

    example
    valueIf(() => true, [])[1, 2, 3]); //=> [1, 2, 3]
    valueIf(() => false, [])[1, 2, 3]); //=> []
    

    Type parameters

    • T

    Parameters

    • predicate: (value: T) => boolean

      Boolean function to determine which value to return.

        • (value: T): boolean
        • Parameters

          • value: T

          Returns boolean

    • defaultValue: T

      The default value to return.

    Returns (value: T) => T

    Finally returns value if predicate returns true, else returns defaultValue.

      • (value: T): T
      • Parameters

        • value: T

        Returns T

Number Functions

Const add

  • add(value1: number, preserveMaxDp?: boolean): (value2: number) => undefined | number
  • Returns the sum of adding value2 to value1.

    memberof

    core

    since

    0.1.0

    see

    increment

    example
    // Integers.
    add(0)(0) //=> 0
    add(1)(1) //=> 2
    add(-1)(-1) //=> -2
    
    // Floats.
    add(0)(0.2) //=> 0.2
    add(0.2)(0.2) //=> 0.4
    add(-0.2, -0.2) //=> -0.4
    
    // Preserving max decimal points.
    add(0.1)(0.2) === 0.3 //=> false
    add(0.1, true)(0.2) === 0.3 //=> true
    

    Parameters

    • value1: number

      The first number to add to.

    • preserveMaxDp: boolean = false

    Returns (value2: number) => undefined | number

    The sum of both numbers.

      • (value2: number): undefined | number
      • Parameters

        • value2: number

          The second number to add.

        Returns undefined | number

Const anyPass

  • anyPass(predicates: PredicateFunction[]): <T>(values: T[]) => boolean
  • Returns true if 1 or more values in values returns true for all predicate functions in predicates.

    memberof

    core

    since

    1.0.0

    see

    anyTrue

    example
    // Integers.
    const isZero = n => n === 0;
    anyPass([isEven])([]) //=> false
    anyPass([isEven])([1, 3, 5]) //=> false
    anyPass([isEven])([1, 2, 3]) //=> true
    anyPass([isEven])([2, 4, 5]) //=> true
    anyPass([isEven, isZero])([0, 2, 4]) //=> true
    

    Parameters

    • predicates: PredicateFunction[]

      The predicate functions that values are checked against.

    Returns <T>(values: T[]) => boolean

    true if 1 or more values in values returns true for all predicate functions in predicates.

      • <T>(values: T[]): boolean
      • Type parameters

        • T

        Parameters

        • values: T[]

          The values to check.

        Returns boolean

Const clamp

  • clamp(min: number, max: number): (value: number) => number
  • Restricts a given value to be inclusively within the range of min to max.

    memberof

    core

    since

    1.0.0

    see

    range

    example
    clamp(1, 3)(-1) //=> 1
    clamp(1, 3)(1) //=> 1
    clamp(1, 3)(3) //=> 3
    clamp(1, 3)(4) //=> 3
    

    Parameters

    • min: number

      Minimum value of the range.

    • max: number

      Maximum value of the range.

    Returns (value: number) => number

    Finally returns a number inclusively within the range of min to max.

      • (value: number): number
      • Parameters

        • value: number

        Returns number

Const decrement

  • decrement(value: number): number
  • Returns value decremented by 1.

    memberof

    core

    since

    0.1.0

    see

    increment

    example
    // Integers.
    decrement(-1) //=> -2
    decrement(0) //=> -1
    decrement(1) //=> 0
    
    // Floats.
    decrement(-1.1) //=> -2.1
    decrement(0.1) //=> -0.1
    decrement(1.1) //=> 0.1
    
    // Others.
    decrement(NaN) //=> NaN
    decrement(Infinity) //=> Infinity
    

    Parameters

    • value: number

      The number to decrement.

    Returns number

    value decremented by 1.

Const equals

  • equals(value1: number): (value2: number) => boolean
  • number-specific (only accepts values of type number) alternative to strictEquals (which compares values of type any). I.e., Finally returns true if value1 is numberically equal to value2, else returns false.

    memberof

    core

    since

    0.1.0

    see

    strictEquals

    example
    equals(1)(1) //=> true
    equals(1)(2) //=> false
    equals(2)(1) //=> false
    

    Parameters

    • value1: number

      First value to compare.

    Returns (value2: number) => boolean

    Finally returns true if value1 is numberically equal to value2, else returns false.

      • (value2: number): boolean
      • Parameters

        • value2: number

          Second value to compare.

        Returns boolean

Const increment

  • increment(value: number): number
  • Returns value incremented by 1.

    memberof

    core

    since

    0.1.0

    see

    decrement

    example
    // Integers.
    increment(-1) //=> 0
    increment(0) //=> 1
    increment(1) //=> 2
    
    // Floats.
    increment(-1.1) //=> -0.1
    increment(0.1) //=> 1.1
    increment(1.1) //=> 2.1
    
    // Others.
    increment(NaN) //=> NaN
    increment(Infinity) //=> Infinity
    

    Parameters

    • value: number

      The number to increment.

    Returns number

    value incremented by 1.

Const integerToHexColor

  • integerToHexColor(value?: number): string
  • Returns value as a valid hexadecimal color string where the hexadecimal value is within the range of 000000 to FFFFFF. Values below this range return the bottom of the range whilst values exceeding this range return the top of the range.

    memberof

    core

    since

    0.1.0

    see

    hexColorToInteger isHexColor

    example
     integerToHexColor(); //=> `#000000`
     integerToHexColor(15); //=> `#00000F`
     integerToHexColor(-1); //=> `#000000`
     integerToHexColor(Infinity); //=> `#FFFFFF`
    

    Parameters

    • value: number = 0

      Integer to convert.

    Returns string

    value as a valid hexadecimal color string

Const isEven

  • isEven(value: number): boolean
  • Returns true if value is even, else returns false.

    memberof

    core

    since

    1.0.0

    example
    // Integers.
    isEven(0) //=> true
    isEven(-1) //=> false
    isEven(1) //=> false
    isEven(-2) //=> true
    isEven(2) //=> true
    
    // Floats.
    isEven(-1.1) //=> false
    isEven(1.1) //=> false
    isEven(-2.2) //=> true
    isEven(2.2) //=> true
    

    Parameters

    • value: number

      The number to check.

    Returns boolean

    true if value is even, else returns false.

Const isFloat

  • isFloat(value?: any): boolean
  • Returns true if value is a float, else returns false.

    memberof

    core

    since

    0.1.0

    see

    isInteger

    example
    // Float values.
    isFloat(-1.1) //=> false
    isFloat(1.1) //=> false
    
    // Non-float values.
    isFloat() //=> false
    isFloat(undefined) //=> false
    isFloat(null) //=> false
    isFloat([]) //=> false
    isFloat([1, '2', 3]) //=> false
    isFloat({}) //=> false
    isFloat({ a: 1, b: '2', c: 3 }) //=> false
    isFloat('') //=> false
    isFloat('foo bar baz') //=> false
    isFloat(true) //=> false
    isFloat(false) //=> false
    isFloat(-1) //=> false
    isFloat(0) //=> false
    isFloat(0.0) //=> false (since JS treats `n.0` as `0`)
    isFloat(1) //=> false
    isFloat(1.0) //=> false
    isFloat(NaN) //=> false
    isFloat(Infinity) //=> false
    

    Parameters

    • Optional value: any

      The value to test.

    Returns boolean

    true if value is a float, else returns false.

Const isInteger

  • isInteger(value?: any): boolean
  • Returns true if value is an integer, else returns false.

    memberof

    core

    since

    0.1.0

    see

    isFloat

    example
    // Integer values.
    isInteger(-1) //=> true
    isInteger(0) //=> true
    isInteger(0.0) //=> true (since JS treats `n.0` as `0`)
    isInteger(1) //=> true
    isInteger(1.0) //=> true
    
    // Non-Integer values.
    isInteger() //=> false
    isInteger(undefined) //=> false
    isInteger(null) //=> false
    isInteger([]) //=> false
    isInteger([1, '2', 3]) //=> false
    isInteger({}) //=> false
    isInteger({ a: 1, b: '2', c: 3 }) //=> false
    isInteger('') //=> false
    isInteger('foo bar baz') //=> false
    isInteger(true) //=> false
    isInteger(false) //=> false
    isInteger(-1.1) //=> false
    isInteger(1.1) //=> false
    isInteger(NaN) //=> false
    isInteger(Infinity) //=> false
    

    Parameters

    • Optional value: any

      The value to test.

    Returns boolean

    true if value is an integer, else returns false.

Const max

  • max(values: number[]): number
  • Returns largest number in values.

    throws

    values cannot be empty.

    memberof

    core

    since

    0.1.0

    example
    // Integers.
    max([]) //=> Error
    max([1, 2, 3]) //=> 3
    
    // Floats.
    max([1, 1.1]) //=> 1.1
    max([1.1, 2.1]) //=> 2.1
    max([-1.1, 1.1]) //=> -1.1
    max([-1.1, -2.1]) //=> -1.1
    

    Parameters

    • values: number[]

    Returns number

    value maxed by 1.

Const maxBy

  • maxBy<T>(mapper: (value: T) => number): (values: T[]) => number
  • Similar to max but maps elements in values to values that are used to determine the largest number.

    throws

    values cannot be empty.

    memberof

    core

    since

    0.1.0

    see

    max

    example
    // Integers.
    const data = [{ value: 1 }, { value: 2 }];
    const getValue = (o: typeof data[number]  ) => o.value;
    
    maxBy(getValue)([]) //=> Error
    maxBy(getValue)(data) //=> 2
    

    Type parameters

    • T

    Parameters

    • mapper: (value: T) => number

      Function that returns a value to compare.

        • (value: T): number
        • Parameters

          • value: T

          Returns number

    Returns (values: T[]) => number

    The largest number.

      • (values: T[]): number
      • Parameters

        • values: T[]

          List of items to map before determining the max.

        Returns number

Const sum

  • sum(numbers: number[]): number
  • Returns the sum of numbers.

    memberof

    core

    since

    1.0.0

    example
    sum([]) //=> 0
    sum([0]) //=> 0
    sum([1]) //=> 1
    sum([1, 2, 3]) //=> 6
    sum([1, -2, 3]) //=> 2
    

    Parameters

    • numbers: number[]

      Numbers to sum.

    Returns number

    Sum of numbers.

Object Functions

Const defaultToValue

  • defaultToValue<TDefaultValue>(defaultValue?: TDefaultValue): <TValue>(value?: Record<string, TValue>) => Record<string, TValue>
  • Finally returns value where missing keys will return defaultValue.

    Useful to ensure an object always return a default value (rather than undefined) for a key that it does not contain:

    example
    const actions = {
        create: 'CREATE',
        fetch: 'FETCH',
    };
    const defaultAction = actions.fetch;
    const defaultToFetch = defaultToValue(defaultAction);
    const defaultedActions = defaultToFetch(actions);
    defaultedActions.foo; //=> 'FETCH'
    
    memberof

    core

    since

    0.1.0

    example
    defaultToValue()()['qux'] //=> undefined
    defaultToValue('foo')({})['qux'] //=> 'foo'
    defaultToValue('foo')({ a: 1, b: '2' })['qux'] //=> 'foo'
    defaultToValue('foo')({ a: 1, b: '2' })['b'] //=> '2'
    

    Type parameters

    • TDefaultValue

    Parameters

    • Optional defaultValue: TDefaultValue

      The default value to return when value does not contain a key (optional, defaults to undefined).

    Returns <TValue>(value?: Record<string, TValue>) => Record<string, TValue>

    value where missing keys will return defaultValue.

      • <TValue>(value?: Record<string, TValue>): Record<string, TValue>
      • Type parameters

        • TValue

        Parameters

        • value: Record<string, TValue> = {}

          The object to apply a default value to (optional, defaults to {}).

        Returns Record<string, TValue>

Const delimitKeys

  • delimitKeys(delimiter?: string): <TValue>(value?: Record<string, TValue>) => string
  • Finally returns a string containing all values' keys delimited by delimiter.

    memberof

    core

    since

    0.1.0

    see

    delimitValues keys

    example
    delimitKeys()({}) //=> ''
    delimitKeys()({ a: 1, b: 2, c: 3 }) //=> 'a,b,c'
    delimitKeys('FOO')({ a: 1, b: 2, c: 3 }) //=> 'aFOObFOOc'
    

    Parameters

    • delimiter: string = ','

      String to delimit keys (optional, defaults to ,).

    Returns <TValue>(value?: Record<string, TValue>) => string

    Finally returns a string containing all values' keys delimited by delimiter.

      • <TValue>(value?: Record<string, TValue>): string
      • Type parameters

        • TValue

        Parameters

        • value: Record<string, TValue> = {}

          Object with keys to delimit.

        Returns string

Const delimitValues

  • delimitValues(delimiter?: string): <TValue>(objectValue?: Record<string, TValue>) => string
  • Finally returns a string containing all objectValues' values delimited by delimiter.

    memberof

    core

    since

    0.1.0

    see

    delimitKeys values

    example
    delimitValues()({}) //=> ''
    delimitValues()({ a: 1, b: 2, c: 3 }) //=> '1,2,3'
    delimitValues('FOO')({ a: 1, b: 2, c: 3 }) //=> '1FOO2FOO3'
    

    Parameters

    • delimiter: string = ','

      String to delimit values (optional, defaults to ,).

    Returns <TValue>(objectValue?: Record<string, TValue>) => string

    Finally returns a string containing all objectValues' values delimited by delimiter.

      • <TValue>(objectValue?: Record<string, TValue>): string
      • Type parameters

        • TValue

        Parameters

        • objectValue: Record<string, TValue> = {}

        Returns string

Const entries

  • entries<T>(value?: Record<string, T>): [string, T][]
  • Returns value's entries as a 2D array containing entry arrays where an entry array is a 2 value tuple containing an entry's key and value.

    memberof

    core

    since

    0.1.0

    see

    entriesCount entriesCountIsAny entriesCountIsNone keys values

    example
     entries(); //=> []
     entries({}); //=> []
     entries({ a: 1, b: 2, c: 3 }); //=> [['a', 1], ['b', 2], ['c', 3]]
    

    Type parameters

    • T

    Parameters

    • Optional value: Record<string, T>

      object to get entries from.

    Returns [string, T][]

    Returns value's entries as a 2D array containing entry arrays (i.e., [['key', 'value'], ...]).

Const entriesCount

  • entriesCount(value?: Record<string, unknown>): number
  • Returns the number of entries in value.

    memberof

    core

    since

    0.1.0

    see

    count entries keys values

    example
     entriesCount(); //=> 0
     entriesCount({}); //=> 0
     entriesCount({ a: 1, b: 2, c: 3 }); //=> 3
    

    Parameters

    • Optional value: Record<string, unknown>

      object with entries to count.

    Returns number

    number of entries in value.

Const entriesCountIsAny

  • entriesCountIsAny(value?: Record<string, unknown>): boolean
  • Returns true if value has 1 or more entries, else returns false.

    memberof

    core

    since

    0.1.0

    see

    entriesCount entriesCountIsNone

    example
     entriesCountIsAny(); //=> false
     entriesCountIsAny({}); //=> false
     entriesCountIsAny({ a: 1, b: 2, c: 3 }); //=> true
    

    Parameters

    • Optional value: Record<string, unknown>

      object with entries to count.

    Returns boolean

    true if value has 1 or more entries, else returns false.

Const entriesCountIsNone

  • entriesCountIsNone(value?: Record<string, unknown>): boolean
  • Inverse of entriesCountIsAny, i.e., returns true if value has 0 entries, else returns false.

    memberof

    core

    since

    0.1.0

    see

    entriesCount entriesCountIsAny

    example
     entriesCountIsNone(); //=> true
     entriesCountIsNone({}); //=> true
     entriesCountIsNone({ a: 1, b: 2, c: 3 }); //=> false
    

    Parameters

    • Optional value: Record<string, unknown>

      object with entries to count.

    Returns boolean

    true if value has 0 entries, else returns false.

Const filterEntries

  • filterEntries<TValue>(predicate?: (value: TValue, key: string) => boolean): (value: Record<string, TValue>) => Record<string, unknown>
  • Finally returns value with entries kept when optional predicate returns true.

    memberof

    core

    since

    0.1.0

    see

    entries filter mapEntries

    example
    filterEntries()({}) //=> {}
    const isEvenNumber = (value: number) => value % 2 === 0;
    filterEntries(isEvenNumber)({}) //=> {}
    filterEntries(isEvenNumber)({ a: 1, b: 2, c: 3 }) //=> { b: 2 }
    

    Type parameters

    • TValue

    Parameters

    • predicate: (value: TValue, key: string) => boolean = ...

      Returns true to keep an entry else the entry is omitted from the. returned object (optional, defaults to keep entries). omitted from the returned object..

        • (value: TValue, key: string): boolean
        • Parameters

          • value: TValue
          • key: string

          Returns boolean

    Returns (value: Record<string, TValue>) => Record<string, unknown>

    Finally returns an object containing value's filtered entries.

      • (value: Record<string, TValue>): Record<string, unknown>
      • Parameters

        • value: Record<string, TValue>

          The object with entries to filter.

        Returns Record<string, unknown>

Const includesKeys

  • includesKeys(...elements: any[]): <T>(value: Record<string, T>) => boolean
  • Finally returns true if value's keys includes all elements, else returns false.

    memberof

    core

    since

    0.1.0

    see

    keys includes includesValues

    example
    includesKeys()({}) //=> false
    includesKeys('a')({}) //=> false
    includesKeys('d')({ a: 1, b: 2, c: 3 }) //=> false
    includesKeys('a')({ a: 1, b: 2, c: 3 }) //=> true
    includesKeys('a', 'b')({ a: 1, b: 2, c: 3 }) //=> true
    

    Parameters

    • Rest ...elements: any[]

      string array of elements representing keys to check for.

    Returns <T>(value: Record<string, T>) => boolean

    Finally returns true if value's keys includes all elements, else returns false.

      • <T>(value: Record<string, T>): boolean
      • Type parameters

        • T

        Parameters

        • value: Record<string, T>

          object with entries to test.

        Returns boolean

Const includesValues

  • includesValues(...elements: any[]): <T>(value: Record<string, T>) => boolean
  • Finally returns true if value's values includes all elements, else returns false.

    memberof

    core

    since

    0.1.0

    see

    includes includesValues values

    example
    includesValues()({}) //=> false
    includesValues(1)({}) //=> false
    includesValues(4)({ a: 1, b: 2, c: 3 }) //=> false
    includesValues(1)({ a: 1, b: 2, c: 3 }) //=> true
    includesValues(1, 2)({ a: 1, b: 2, c: 3 }) //=> true
    includesValues(1, '2')({ a: 1, b: '2', c: 3 }) //=> true
    

    Parameters

    • Rest ...elements: any[]

      string array of elements representing values to check for.

    Returns <T>(value: Record<string, T>) => boolean

    Finally returns true if value's values includes all elements, else returns false.

      • <T>(value: Record<string, T>): boolean
      • Type parameters

        • T

        Parameters

        • value: Record<string, T>

          object with entries to test.

        Returns boolean

Const injectKeys

  • injectKeys<TValue>(keys?: string[], defaultValue?: TValue): (valueObject: Record<string, TValue>) => Record<string, TValue>
  • Finally returns valueObject with all keys (optional, defaults to []) injected as entries with a value of defaultValue (optional, defaults to undefined).

    memberof

    core

    since

    0.1.0

    see

    injectKeys pickKeys

    example
    injectKeys()({}) //=> {}
    injectKeys(['b', 'c'])({ a: 1 }) //=> { a: 1, b: undefined, c: undefined }
    injectKeys(['b', 'c'], 2)({ a: 1 }) //=> { a: 1, b: 2, c: 2 }
    

    Type parameters

    • TValue

    Parameters

    • keys: string[] = []

      String array of keys to inject (optional, defaults to []).

    • Optional defaultValue: TValue

      The default value of injected entries (optional, defaults to undefined).

    Returns (valueObject: Record<string, TValue>) => Record<string, TValue>

    Finally returns valueObject with all keys injected as entries with a value of defaultValue.

      • (valueObject: Record<string, TValue>): Record<string, TValue>
      • Parameters

        • valueObject: Record<string, TValue>

          The object to inject keys into.

        Returns Record<string, TValue>

Const injectMissingKeys

  • injectMissingKeys<TValue>(keys?: string[], defaultValue?: TValue): (valueObject: Record<string, TValue>) => Record<string, TValue>
  • Finally returns valueObject with keys (optional, defaults to []) that were missing injected as entries with a value of defaultValue (optional, defaults to undefined).

    memberof

    core

    since

    0.1.0

    see

    injectKeys

    example
    injectMissingKeys()({}) //=> {}
    injectMissingKeys(['b', 'c'])({ a: 1 }) //=> { a: 1, b: undefined, c: undefined }
    injectMissingKeys(['b', 'c'], 2)({ a: 1 }) //=> { a: 1, b: 2, c: 2 }
    

    Type parameters

    • TValue

    Parameters

    • keys: string[] = []

      String array of keys to inject (optional, defaults to []).

    • Optional defaultValue: TValue

      The default value of injected entries (optional, defaults to undefined).

    Returns (valueObject: Record<string, TValue>) => Record<string, TValue>

    Finally returns valueObject with missing keys injected as entries with a value of defaultValue.

      • (valueObject: Record<string, TValue>): Record<string, TValue>
      • Parameters

        • valueObject: Record<string, TValue>

          The object to inject keys into.

        Returns Record<string, TValue>

Const invertEntries

  • invertEntries<TValue>(value?: Record<string, TValue>): Record<string, TValue>
  • Finally returns value with the keys and values of entries inverted.

    memberof

    core

    since

    0.1.0

    example
    invertEntries() //=> {}
    invertEntries({}) //=> {}
    invertEntries({ a: 'foo', b: 2, c: 'bar }) //=> { foo: 'a', '2': 'b', bar: 'c' }
    

    Type parameters

    • TValue

    Parameters

    • value: Record<string, TValue> = {}

      The object with entries to invert (optional, defaults to {}).

    Returns Record<string, TValue>

    Finally returns an object containing entries of both value1 & value2.

Const isObject

  • isObject(value: any): boolean
  • Returns true if value is an object, else returns false.

    memberof

    core

    since

    0.1.0

    see

    isArray

    example
    // Object values.
    isObject({}); //=> true
    isObject({ a: 1, b: 2, c: 3 }); //=> true
    isObject({ a: 1, b: 2, c: 3 } as Record<string, number>); //=> true
    
    // Non-object values.
     isObject(); //=> false
     isObject(undefined); //=> false
     isObject(null); //=> false
     isObject([]); //=> false
     isObject([1, 2, 3]); //=> false
     isObject('foo bar baz'); //=> false
     [-1, 0, 1].map(isObject); //=> [false, false, false]
     [true, false].map(isObject); //=> [false, false]
    

    Parameters

    • value: any

      object to test.

    Returns boolean

    true if value is an object, else returns false

Const keys

  • keys(value?: Record<string, unknown>): string[]
  • Returns a string array of value's keys.

    memberof

    core

    since

    0.1.0

    see

    values

    example
    keys(); //=> []
    keys({}); //=> []
    keys({ a: 1, b: 2, c: 3 }); //=> ['a', 'b', 'c']
    

    Parameters

    • Optional value: Record<string, unknown>

      object with keys to use.

    Returns string[]

    Returns a string array of value's keys

Const mapEntries

  • mapEntries<TValue, TMapped>(options?: MapEntriesOptions<TValue, TMapped>): (objectValue: Record<string, TValue>) => Record<string, TMapped>
  • Finally returns objectValue with all entries mapped using optional MapEntriesOptions to provide new keys and values.

    memberof

    core

    since

    0.1.0

    see

    entries map reduceEntries

    example
    const appendFoo = (__: number, k: string) => k + 'Foo';
    mapEntries()({}) //=> {}
    mapEntries({ keyMapper: appendFoo })({}) //=> {}
    mapEntries({ keyMapper: appendFoo })({ a: 1, b: 2, c: 3 }) //=> { aFoo: 1, bFoo: 2, cFoo: 3 }
    const doubleNumber = (v: number) => v * 2;
    mapEntries({ valueMapper: doubleNumber })({ a: 1, b: 2, c: 3 }) //=> { a: 2, b: 4, c: 6 }
    const isEvenNumber = (value: number) => value % 2 === 0;
    mapEntries({ keepEntry: isEvenNumber })({ a: 1, b: 2, c: 3 }) //=> { b: 2 }
    

    Type parameters

    • TValue

    • TMapped

    Parameters

    • options: MapEntriesOptions<TValue, TMapped> = {}

    Returns (objectValue: Record<string, TValue>) => Record<string, TMapped>

    Finally returns an object containing objectValue's mapped entries.

      • (objectValue: Record<string, TValue>): Record<string, TMapped>
      • Parameters

        • objectValue: Record<string, TValue>

          The object with entries to map.

        Returns Record<string, TMapped>

Const mapKeys

  • mapKeys<TValue>(transformer?: (__: TValue, key: string) => string): (objectValue: Record<string, TValue>) => Record<string, unknown>
  • Finally returns objectValue with the keys of all entries mapped using optional transformer.

    memberof

    core

    since

    0.1.0

    see

    keys mapEntries mapValues

    example
    const appendFoo = (__: number, k: string) => k + 'Foo';
    mapKeys()({}) //=> {}
    mapKeys(appendFoo)({}) //=> {}
    mapKeys(appendFoo)({ a: 1, b: 2, c: 3 }) //=> { aFoo: 1, bFoo: 2, cFoo: 3 }
    

    Type parameters

    • TValue

    Parameters

    • transformer: (__: TValue, key: string) => string = ...

      Returns the next key (optional, defaults to return the original key).

        • (__: TValue, key: string): string
        • Parameters

          • __: TValue
          • key: string

          Returns string

    Returns (objectValue: Record<string, TValue>) => Record<string, unknown>

    Finally returns an object containing objectValue's mapped entries.

      • (objectValue: Record<string, TValue>): Record<string, unknown>
      • Parameters

        • objectValue: Record<string, TValue>

          The object with entries keys to map.

        Returns Record<string, unknown>

Const mapValues

  • mapValues<TValue>(transformer?: (value: TValue, __: string) => TValue): (objectValue: Record<string, TValue>) => Record<string, TValue>
  • Finally returns objectValue with the values of all entries mapped using optional transformer.

    memberof

    core

    since

    0.1.0

    see

    mapEntries mapKeys values

    example
    const doubleNumber = (v: number) => v * 2;
    mapValues()({}) //=> {}
    mapValues(doubleNumber)({}) //=> {}
    mapValues(doubleNumber)({ a: 1, b: 2, c: 3 }) //=> { a: 2, b: 4, c: 6 }
    

    Type parameters

    • TValue

    Parameters

    • transformer: (value: TValue, __: string) => TValue = ...

      Returns the next value (optional, defaults to return the original value).

        • (value: TValue, __: string): TValue
        • Parameters

          • value: TValue
          • __: string

          Returns TValue

    Returns (objectValue: Record<string, TValue>) => Record<string, TValue>

    Finally returns an object containing objectValue's mapped entries.

      • (objectValue: Record<string, TValue>): Record<string, TValue>
      • Parameters

        • objectValue: Record<string, TValue>

          The object with entries values to map.

        Returns Record<string, TValue>

Const mergeEntries

  • mergeEntries<TValue1>(value1?: Record<string, TValue1>): <TValue2>(value2?: Record<string, TValue2>) => {}
  • Finally returns an object containing all elements in both value1 & value2 where entries with identical keys will be entries from value2.

    memberof

    core

    since

    0.1.0

    see

    concat union

    example
    mergeEntries()() //=> {}
    mergeEntries({})({}) //=> {}
    mergeEntries({ a: 1, b: 2 })({ c: 3, d: 4 }) //=> { a: 1, b: 2, c: 3, d: 4 }
    mergeEntries({ a: 1, b: 2 })({ a: 1, b: 3 }) //=> { a: 1, b: 3 }
    mergeEntries({ a: 1, b: 2 })({}) //=> { a: 1, b: 3 }
    mergeEntries({})({ c: 3, d: 4 }) //=> { c: 3, d: 4 }
    

    Type parameters

    • TValue1

    Parameters

    • value1: Record<string, TValue1> = {}

      The first object to merge.

    Returns <TValue2>(value2?: Record<string, TValue2>) => {}

    Finally returns an object containing entries of both value1 & value2.

      • <TValue2>(value2?: Record<string, TValue2>): {}
      • Type parameters

        • TValue2

        Parameters

        • value2: Record<string, TValue2> = {}

          The second object to merge.

        Returns {}

Const objectOr

  • objectOr(defaultValue?: Record<string, unknown>): (value: any) => Record<string, unknown>
  • Finally returns value if it is valid via isObject, else returns defaultValue.

    memberof

    core

    since

    0.1.0

    see

    valueIf

    example
    objectOr()(null); //=> {} as Record<string, unknown>
    objectOr({ a: 1 })(null); //=> { a: 1 }
    objectOr({ a: 1 })({ a: 1, b: 2, c: 3 }); //=> { a: 1, b: 2, c: 3 }
    

    Parameters

    • defaultValue: Record<string, unknown> = {}

      The default value to return (optional, defaults to Record<string, unknown>).

    Returns (value: any) => Record<string, unknown>

    Finally returns value if it is valid via isObject, else returns defaultValue

      • (value: any): Record<string, unknown>
      • Parameters

        • value: any

          Value to test.

        Returns Record<string, unknown>

Const objectToString

  • objectToString<TValue>(value: Record<string, TValue>, indentSpaces?: number): string
  • Returns value as a string.

    memberof

    core

    since

    0.1.0

    example
    objectToString({}) //=> '{}'
    objectToString({ a: 1, b: '2', c: 3}) //=> '{"a":1,"b":"2","c":3}'
    

    Type parameters

    • TValue

    Parameters

    • value: Record<string, TValue>

      Object to convert to string.

    • indentSpaces: number = 0

      Optional number of spaces to indent the object (defaults to 0, i.e., no spacing).

    Returns string

    value as a string.

Const omitKeys

  • omitKeys<TValue>(...keys: string[]): (value: Record<string, TValue>) => Record<string, unknown>
  • Finally returns value where entries with a key included in keys are omited.

    memberof

    core

    since

    0.1.0

    see

    filterEntries

    example
    omitKeys()({}) //=> {}
    omitKeys('a', 'b')({}) //=> {}
    omitKeys('a', 'b)({ a: 1, b: 2, c: 3 }) //=> { c: 3 }
    omitKeys('d')({ a: 1, b: 2, c: 3 }) //=> { a: 1, b: 2, c: 3 }
    

    Type parameters

    • TValue

    Parameters

    • Rest ...keys: string[]

      string array of keys to omit.

    Returns (value: Record<string, TValue>) => Record<string, unknown>

    Finally returns value where entries with a key included in keys are omited.

      • (value: Record<string, TValue>): Record<string, unknown>
      • Parameters

        • value: Record<string, TValue>

          The object with keys to filter.

        Returns Record<string, unknown>

Const pickKeys

  • pickKeys<TValue>(...keys: string[]): (value: Record<string, TValue>) => Record<string, unknown>
  • Inverse of omitKeys, i.e., finally returns value where entries have a key included in keys.

    memberof

    core

    since

    0.1.0

    see

    omitKeys

    example
    pickKeys()({}) //=> {}
    pickKeys('a', 'b')({}) //=> {}
    pickKeys('a', 'b)({ a: 1, b: 2, c: 3 }) //=> { a: 1, b: 2 }
    pickKeys('d')({ a: 1, b: 2, c: 3 }) //=> {}
    

    Type parameters

    • TValue

    Parameters

    • Rest ...keys: string[]

      String array of keys to pick.

    Returns (value: Record<string, TValue>) => Record<string, unknown>

    Finally returns an object containing value's entries with keys that are included in keys.

      • (value: Record<string, TValue>): Record<string, unknown>
      • Parameters

        • value: Record<string, TValue>

          The object with keys to pick.

        Returns Record<string, unknown>

Const pluckKey

  • pluckKey<TValue>(key: string): (valueObject: Record<string, TValue>) => TValue
  • Finally returns the value at key in objectValue if found, else returns undefined.

    Intended for curried usage hence pluckKey accepts a key to generate a "plucking" function that will finally return the value of objectValue at key:

    example
    const values = [{ name: 'foo' }, { name: 'bar' }, { name: 'baz' }];
    const pluckName = pluckKey('name');
    values.map(pluckName); //=> ['foo', 'bar', 'baz']
    
    memberof

    core

    since

    0.1.0

    see

    pluckKeys pickKeys

    example
    pluckKey('a')({}) //=> undefined
    pluckKey('a')({ a: 1, b: 2, c: 3 }) //=> 1
    pluckKey('d')({ a: 1, b: 2, c: 3 }) //=> undefined
    

    Type parameters

    • TValue

    Parameters

    • key: string

      String to pluck.

    Returns (valueObject: Record<string, TValue>) => TValue

    Finally returns the value at key in objectValue.

      • (valueObject: Record<string, TValue>): TValue
      • Parameters

        • valueObject: Record<string, TValue>

          The object with keys to pluck.

        Returns TValue

Const pluckKeys

  • pluckKeys<TValue>(key: string): (values: Record<string, TValue>[]) => TValue[]
  • Applies pluckKey to an array of objects, i.e., returns the value at key for all objects in values. Serves as a convenient alternative to mapping pluckKey over an array of objects.

    Similar to pluckKey, pluckKeys is intended for curried usage hence accepts a key to generate a "plucking" function that will finally return the values at key in all objects in values:

    example
    const values = [{ name: 'foo' }, { name: 'bar' }, { name: 'baz' }];
    const pluckNames = pluckKeys('name');
    pluckNames(values); //=> ['foo', 'bar', 'baz']
    
    memberof

    core

    since

    0.1.0

    see

    pluckKey

    example
    pluckKeys('name')([]) //=> []
    pluckKeys('name')([{}]) //=> [undefined]
    pluckKeys('name')([{ name: 'foo' }, { name: 'bar' }, { name: 'baz' }]) //=> ['foo', 'bar', 'baz']
    pluckKeys('qux')([{ name: 'foo' }, { name: 'bar' }, { name: 'baz' }]) //=> [undefined, undefined, undefined]
    

    Type parameters

    • TValue

    Parameters

    • key: string

      String to pluck.

    Returns (values: Record<string, TValue>[]) => TValue[]

    An array of values at key in all objects in values.

      • (values: Record<string, TValue>[]): TValue[]
      • Parameters

        • values: Record<string, TValue>[]

          Array of objects with keys to pluck.

        Returns TValue[]

Const reduceEntries

  • reduceEntries<TMapped>(initial?: TMapped, transformer?: (previousValue: TMapped, value: any, key: string) => TMapped, includeNested?: boolean): (objectValue: Record<string, any>) => TMapped
  • Finally returns objectValue's entries reduced to a single value using initial as the starting value and transformer to provide the next value.

    Nested objects can optionally be reduced if includeNested is true, else only the root object objectValue is reduced.

    memberof

    core

    since

    0.1.0

    see

    entries map mapEntries reduce

    example
    reduceEntries()({}) //=> {}
    const concatKeys = (prev: string, __: number, key: string) => prev + key;
    reduceEntries('', concatKeys)({}) //=> ''
    reduceEntries('', concatKeys)({ a: 1, b: 2, c: 3 }) //=> 'abc'
    const sumNumbers = (prev: number, value: number) => prev + value;
    reduceEntries(0, sumNumbers)({ a: 1, b: 2, c: 3 }) //=> 6
    
    // Reduce values of nested objects.
    reduceEntries(0, sumNumbers, true)({ a: 1, first: { b: 2, second: { c: 3 } } }) //=> 6
    

    Type parameters

    • TMapped

    Parameters

    • initial: TMapped = ...

      The first value of prev passed to the transformer.

    • transformer: (previousValue: TMapped, value: any, key: string) => TMapped = ...

      Returns the next value (optional, defaults to return the original value).

        • (previousValue: TMapped, value: any, key: string): TMapped
        • Parameters

          • previousValue: TMapped
          • value: any
          • key: string

          Returns TMapped

    • includeNested: boolean = false

      Optional (defaults to false) boolea, if true, nested objects are reduced using transformer, else only the root object objectValue is reduced.

    Returns (objectValue: Record<string, any>) => TMapped

    An object containing objectValue's mapped entries.

      • (objectValue: Record<string, any>): TMapped
      • Parameters

        • objectValue: Record<string, any>

          The object with entries to reduce.

        Returns TMapped

Const values

  • values<T>(value?: Record<string, T>): T[]
  • Returns an array of value's values.

    memberof

    core

    since

    0.1.0

    see

    keys

    example
     values(); //=> []
     values({}); //=> []
     values({ a: 1, b: 2, c: 3  }); //=> [1, 2, 3]
    

    Type parameters

    • T

    Parameters

    • Optional value: Record<string, T>

      object with values.

    Returns T[]

    Returns an array of value's values.

Other Functions

Const toggleStrings

  • toggleStrings(toggleMap: Record<string, boolean>, delimiter?: string): (preserved: string) => string
  • Convenience method for generating strings with conditional sub-strings. Appends delimited muxMap keys that have a true value to verbatimStr.

    memberof

    core

    since

    1.0.0

    example
    toggleStrings({})('') //=> ''
    toggleStrings({})('foo bar') //=> 'foo bar'
    toggleStrings({ baz: true, qux: true })('foo bar') //=> 'foo bar baz qux'
    toggleStrings({ baz: false, qux: false })('foo bar') //=> 'foo bar'
    
    // Delimiter.
    toggleStrings({ baz: true, qux: true }, '-')('foo bar') //=> 'foo bar-baz-qux'
    

    Parameters

    • toggleMap: Record<string, boolean>
    • delimiter: string = ' '

      Delimits appended strings (optional, defaults to ' ').

    Returns (preserved: string) => string

    Finally returns a string containing the verbatimStr appended with the delimited keys of entries in stringsToToggleMap that have a true value.

      • (preserved: string): string
      • Parameters

        • preserved: string

        Returns string

Promise Functions

Const allSettled

  • allSettled<T>(promises: Promise<T>[]): Promise<ResolvedPromise<T>[]>
  • Returns an array of Promise<ResolvedPromise> when all promises have resolved to either fulfilled or rejected.

    Serves as a functional polyfilled alternative to Promise.allSettled hence is useful regardless of older browsers/runtimes when running several Promises & operating on their resolved data:

    example
    const fetchUsers = page => Math.random() > 0.5 // Simulate potential error.
        ? Promise.resolve([])
        : new Promise((__, reject) => setTimeout(reject, 1000));
    const fetchUserData = async () => {
        // Run all promises regardless of resolved status.
        const resolved = await allSettled(pageNumbers.map(fetchUsers(1), fetchUsers(2)));
        // Omit rejected `Promises`.
        const fulfilled = resolved.filter(v => v.status === 'fulfilled');
        const users = fulfilled.map(v => v.value);
    };
    
    memberof

    core

    since

    0.1.0

    see

    allSettledFilterStatus

    example
    await allSettled([Promise.resolve(1), Promise.reject(2)]); //=> [{ status: 'fulfilled', value: 1 }, { status: 'rejected', value: 2 }]
    

    Type parameters

    • T

    Parameters

    • promises: Promise<T>[]

      Promises to run.

    Returns Promise<ResolvedPromise<T>[]>

    An array of Promise<ResolvedPromise> when all promises have resolved to either fulfilled or rejected.

Const allSettledFilterStatus

  • allSettledFilterStatus(status?: ResolvedPromiseStatus): <T>(promises: Promise<T>[]) => Promise<ResolvedPromise<T>[]>
  • Finally returns a filtered array of ResolvedPromise where all ResolvedPromise.status are status.

    Serves as a convenient alternative to collecting resolved Promises from allSettled with a specific resolved status:

    example
    const fetchUsers = page => Math.random() > 0.5 // Simulate potential error.
        ? Promise.resolve([])
        : new Promise((__, reject) => setTimeout(reject, 1000));
    const fetchUserData = async () => {
        pendingPromises = pageNumbers.map(fetchUsers(1), fetchUsers(2));
        // Collect all fulfilled promises.
        const fulfilled = await allSettledFilterStatus('fulfilled')(pendingPromises);
        const users = fulfilled.map(v => v.value);
    };
    
    memberof

    core

    since

    0.1.0

    see

    allSettled

    example
    const pendingPromises = [Promise.resolve(1), Promise.reject(2)];
    await allSettledFilterStatus()(pendingPromises); //=> [{ status: 'fulfilled', value: 1 }]
    await allSettledFilterStatus('fulfilled')(pendingPromises); //=> [{ status: 'fulfilled', value: 1 }]
    await allSettledFilterStatus('rejected')(pendingPromises); //=> [{ status: 'rejected', value: 2 }]
    

    Parameters

    • status: ResolvedPromiseStatus = ...

      String to filter ResolvedPromises by (optional, defaults to fulfilled).

    Returns <T>(promises: Promise<T>[]) => Promise<ResolvedPromise<T>[]>

    Finally returns a filtered array of ResolvedPromise where all ResolvedPromise.status are status.

      • <T>(promises: Promise<T>[]): Promise<ResolvedPromise<T>[]>
      • Type parameters

        • T

        Parameters

        • promises: Promise<T>[]

          Promises to run.

        Returns Promise<ResolvedPromise<T>[]>

Const delayFor

  • delayFor(delayMs?: number): Promise<unknown>
  • Returns a Promise resolving to delayMs after waiting for delayMs milliseconds.

    Useful for pausing asynchronous operations for a specific duration:

    example
    const delayedLogNumbers = async numbers =>
        numbers.forEach(async n => {
            await delayFor(2000);
            console.log(n); // Log `n` after `2000`ms
        });
    
    memberof

    core

    since

    0.1.0

    see

    opRuntime

    example
    await delayFor(); //=> (pauses async operations for `1000`ms)
    await delayFor(2000); //=> (pauses async operations for `2000`ms)
    

    Parameters

    • delayMs: number = 1000

      Number of milliseconds to delay (optional, defaults to 1000ms)

    Returns Promise<unknown>

    A Promise resolving to delayMs after waiting for delayMs milliseconds.

Const promiseAll

  • promiseAll<TPoolResults>(poolSize?: number, onPoolComplete?: (poolResults: TPoolResults[]) => void): <T>(promises: Promise<T>[]) => Promise<T[]>
  • Concurrency-controlled alternative to Promise.all. I.e., finally returns a Promise containing an array of Promise values by asynchronously running promises via a Promise pool where concurrency is limited to poolSize, and each pool iteration's results are reactable via onPoolComplete.

    Useful when asynchronously running several Promises in parallel with controlled concurrency:

    example
    // Simulate collecting a page as a number.
    const fetchPages = n => new Promise(r => setTimeout(() => r(n), n));
    
    let pages = [];
    const onPoolComplete = (poolPages: number) => pages = [...pages, ...poolPages];
    const poolSize = 2;
    const pendingPromises = [fetchPages(100), fetchPages(200), fetchPages(300), fetchPages(400)];
    await promiseAll(poolSize, onPoolComplete)(pendingPromises);
    pages //=> [[100,200], [300, 400]]
    
    memberof

    core

    since

    0.1.0

    see

    promiseAllProgress promiseSequence

    example
    let results = [];
    const onPoolComplete = results => results = [..results, results];
    const delayedWork = duration => new Promise(r => setTimeout(() => r(duration), duration));
    const pendingPromises = [delayedWork(100), delayedWork(200), delayedWork(300), delayedWork(400)];
    
    await promiseAll(onPoolComplete)(pendingPromises); // `Infinite` concurrency.
    results; //=> [100, 200, 300, 400]
    
    results = []; // Reset `results`.
    await promiseAll(onPoolComplete, 2)(pendingPromises); // Concurrency `2`.
    results //=> [[100, 200], [300, 400]]
    

    Type parameters

    • TPoolResults

    Parameters

    • poolSize: number = ...

      Number of promises to run per pool iteration (optional, defaults to Infinity).

    • onPoolComplete: (poolResults: TPoolResults[]) => void = ...

      Called when results are collected from running a Promise pool (optional, defaults to return undefined).

        • (poolResults: TPoolResults[]): void
        • Parameters

          • poolResults: TPoolResults[]

          Returns void

    Returns <T>(promises: Promise<T>[]) => Promise<T[]>

    Finally returns a Promise containing an array of Promise values.

      • <T>(promises: Promise<T>[]): Promise<T[]>
      • Type parameters

        • T

        Parameters

        • promises: Promise<T>[]

          Promises to run.

        Returns Promise<T[]>

Const promiseAllProgress

  • promiseAllProgress<T>(onProgress?: PromiseAllProgressFunction<T>): (promises: Promise<T>[]) => Promise<T[]>
  • Convenient alternative to Promise.all that runs all promises (calling onProgress when each Promise resolves) before finally returning an array of Promises.

    Useful when responding to the completion of each Promise:

    example
    const updateLoadingBar = percent => {
        // ...update loading bar.
    };
    const fetchUser = id => new Promise(r => setTimeout(() => r('user ' + id), 1000));
    const onProgress = (percentComplete, value) => updateLoadingBar(percentComplete);
    const pendingUsers = [fetchUser(1), fetchUser(2), fetchUser(3), fetchUser(4)];
    // Fetch users & update loading bar as users are fetched.
    const users = promiseAllProgress(onProgress)(pendingUsers);
    
    memberof

    core

    since

    0.1.0

    example
    let percentages = [];
    const onProgress = (percentage, value) => [...percentages, { percentage, value }];
    const delayedWork = duration => new Promise(r => setTimeout(() => r(duration), duration));
    const pendingPromises = [delayedWork(1000), delayedWork(2000)];
    await promiseAllProgress(onProgress)(pendingPromises); //=> [1000, 2000]
    percentages; //=> [{ percentage: 0, value: 50 }, { percentage: 0, value: 100 }]
    

    Type parameters

    • T

    Parameters

    • onProgress: PromiseAllProgressFunction<T> = ...

      Called for each resolved Promise.

    Returns (promises: Promise<T>[]) => Promise<T[]>

    Finally returns an array of Promise<ResolvedPromise> when all promises have resolved to either fulfilled or rejected.

      • (promises: Promise<T>[]): Promise<T[]>
      • Parameters

        • promises: Promise<T>[]

          Promises to run.

        Returns Promise<T[]>

Const promiseFilter

  • promiseFilter<T>(predicate?: (value: T, index: number) => Promise<boolean>): (array: T[]) => Promise<T[]>
  • Asynchronous alternative to filter, i.e., finally returns a Promise containing array elements where predicate returns a Promise boolean resolve to true, else elements are omitted.

    memberof

    core

    since

    0.1.0

    see

    filter promiseAll

    example
    const promiseIsEven = n => Promise.resolve(n % 2 === 0);
    await promiseFilter(promiseIsEven)([]) //=> []
    await promiseFilter(promiseIsEven)([1, 2, 3]) //=> [2]
    

    Type parameters

    • T

    Parameters

    • predicate: (value: T, index: number) => Promise<boolean> = ...

      Returns a Promise boolean trueto keepvalue, else returns falseto omitvalue`.

        • (value: T, index: number): Promise<boolean>
        • Parameters

          • value: T
          • index: number

          Returns Promise<boolean>

    Returns (array: T[]) => Promise<T[]>

    Finally returns a Promise resolving to array elements where predicate returned a Promise resolving to true.

      • (array: T[]): Promise<T[]>
      • Parameters

        • array: T[]

          Array to filter.

        Returns Promise<T[]>

Const promiseReduce

  • promiseReduce<T, TMapped>(initial: TMapped, transformer?: (prevValue: TMapped, value: T) => TMapped): (promises: Promise<T>[]) => Promise<TMapped>
  • Single-value alternative to promiseSequence. I.e., synchronously runs promises in sequential order using initialValue as the starting value and transformer to provide a new value based on the previous value (i.e., prevValue) for each Promise to finally return a Promise containing the a single value.

    Useful when synchronously running several Promises where subsequent Promises may depend on the result of the previous Promise:

    example
    const fetchDelayedString = (duration, s) => new Promise(r => setTimeout(() => r(s), duration));
    const initialString = '';
    const joinStrings = (prevString, s) => prevString + s;
    
    const pendingPromises = [
        fetchDelayedString(300, 'foo'),
        fetchDelayedString(200, 'bar'),
        fetchDelayedString(100, 'baz')
    ];
    const results = await promiseReduce(initialString, joinStrings)(pendingPromises);
    results; //=> 'foobarbaz'
    
    memberof

    core

    since

    0.1.0

    see

    promiseSequence

    Type parameters

    • T

    • TMapped

    Parameters

    • initial: TMapped

      Starting value.

    • transformer: (prevValue: TMapped, value: T) => TMapped = ...

      Accepts prevValue to return a new value.

        • (prevValue: TMapped, value: T): TMapped
        • Parameters

          • prevValue: TMapped
          • value: T

          Returns TMapped

    Returns (promises: Promise<T>[]) => Promise<TMapped>

    Finally returns a Promise containing an array of Promise values.

      • (promises: Promise<T>[]): Promise<TMapped>
      • Parameters

        • promises: Promise<T>[]

          Promises to run.

        Returns Promise<TMapped>

Const promiseSequence

  • promiseSequence<T, TMapped>(promises: Promise<T>[]): Promise<TMapped[]>
  • Sequential alternative to promiseAll. I.e., synchronously runs promises in sequential order to return a Promise containing an array of values.

    Useful when synchronously running several Promises in an ordered sequence:

    example
    const delayedNumber = duration => new Promise(r => setTimeout((duration) => r(duration), duration));
    const getLongTask = () => delayedNumber(1000);
    const getShortTask = () => delayedNumber(0);
    
    let result = promiseSequence([getLongTask(), getShortTask()]);
    // `Promise`s are run in sequence hence `getLongTask` result is first.
    result //=> [1000, 0]
    
    memberof

    core

    since

    0.1.0

    see

    promiseAll promiseReduce

    Type parameters

    • T

    • TMapped

    Parameters

    • promises: Promise<T>[]

      Promises to run.

    Returns Promise<TMapped[]>

    Returns a Promise containing an array of values

Const promiseStatus

  • promiseStatus<T>(promise: Promise<T>): Promise<PromiseStatusString>
  • Returns a string representing the promise's statuswhere the string is either'fulfilled', 'rejected', or 'pending'`.

    memberof

    core

    since

    0.1.0

    example
    await promiseStatus(Promise.resolve(1)); //=> 'fulfilled'
    await promiseStatus(Promise.reject(1)); //=> 'rejected'
    await promiseStatus(new Promise(() => undefined); //=> 'pending'
    

    Type parameters

    • T

    Parameters

    • promise: Promise<T>

      Promise to check.

    Returns Promise<PromiseStatusString>

    A string representing the promise's status`.

Const promisify

  • promisify<TValue>(testFunction: AnyFunction): (...args: any[]) => Promise<TValue>
  • Provides a basic method to convert testFunction into an altered function that returns a Promise, which can finally be called to return testFunction's error or result depending on resolution of its returned Promise.

    Useful when updating legacy functions to use Promises:

    example
    const isEven = n => n % 2 === 0;
    const delayedIsEven = (n, callback) => setTimeout(
        () => isEven(n) ? callback(undefined, 'is even') : callback('not even')
    );
    
    const promisedDelayedIsEven = promisify(delayedIsEven);
    await promisedDelayedIsEven(1); //=> 'not even'
    await promisedDelayedIsEven(2); //=> 'is even'
    
    memberof

    core

    since

    0.1.0

    Type parameters

    • TValue = any

    Parameters

    • testFunction: AnyFunction

      The legacy non-Promise function that accepts a callback function (i.e., (error, result) => undefined). convert to return a Promise.

    Returns (...args: any[]) => Promise<TValue>

    testFunction altered to finally return its callback data via a Promise.

      • (...args: any[]): Promise<TValue>
      • Parameters

        • Rest ...args: any[]

          The arguments for the original testFunction.

        Returns Promise<TValue>

Const rejectAfter

  • rejectAfter(timeoutMs?: number, error?: Error): <T>(promise: Promise<T>) => Promise<T>
  • Finally returns error as a rejected Promise if timeout is exceeded, else returns promise's value.

    Useful for running a Promise within a fixed duration:

    const fetchUsers = () => {
        // ...returns `Promise`.
    };
    const users;
    const timeout = 2000;
    try {
        users = rejectAfter(timeout)(fetchUsers()); // Actual value if `timeout` isn't exceeded.
    } catch (e) {
        users = []; // Default value if `timeout` exceeded.
    }
    
    memberof

    core

    since

    0.1.0

    see

    rejectAllAfter

    example
    await rejectAfter(2000)(async () => setTimeout(r => r('fulfilled'), 1000)); //=> 'fulfilled'
    await rejectAfter(2000)(async () => setTimeout(r => r('fulfilled'), 3000)); //=> 'Error'
    

    Parameters

    • timeoutMs: number = 10000
    • error: Error = ...

      An Error to return if timeout is exceeded (optional, defaults to a generic Error).

    Returns <T>(promise: Promise<T>) => Promise<T>

    Finally returns error as a rejected Promise if timeout is exceeded, else returns promise's value.

      • <T>(promise: Promise<T>): Promise<T>
      • Type parameters

        • T

        Parameters

        • promise: Promise<T>

          A promise to potentially reject.

        Returns Promise<T>

Const rejectAllAfter

  • rejectAllAfter(timeoutMs?: number, error?: Error): <T>(promises: Promise<T>[]) => Promise<void | T[]>
  • Finally returns error as a rejected Promise if timeout is exceeded, else returns an array of values for each Promise in promises.

    Useful for running several Promises within a fixed duration:

    example
    const fetchUsers = () => {
        // ...returns `Promise`.
    };
    const fetchPages = () => {
        // ...returns `Promise`.
    };
    const timeout = 2000;
    let users;
    let pages;
    try {
        const promises = [fetchUsers(), fetchPages()];
        // Actual values if all `promises` complete before `timeout`.
        const [fetchedUsers, fetchedPages] = rejectAllAfter(timeout)(promises);
    } catch (e) {
       // ...error handling.
    
        // Default values if `timeout` exceeded.
        users = [];
        pages = [];
    }
    
    memberof

    core

    since

    0.1.0

    see

    rejectAfter

    example
    const timeout = 2000;
    const longRunningTask = async (duration: number) => await new Promise(
        r => setTimeout(() => r('fulfilled'), duration)
    );
    const tasksBeforeTimeout = [
        longRunningTask(timeout / 2),
        longRunningTask(timeout / 3),
    ];
    const tasksAfterTimeout = [
        longRunningTask(timeout * 2),
        longRunningTask(timeout * 3),
    ];
    
    await rejectAllAfter(timeout)(tasksBeforeTimeout)); //=> ['fulfilled', 'fulfilled']
    await rejectAllAfter(timeout)(tasksAfterTimeout); //=> 'Error'
    

    Parameters

    • timeoutMs: number = 10000
    • error: Error = ...

      An Error to return if timeout is exceeded (optional, defaults to generic Error).

    Returns <T>(promises: Promise<T>[]) => Promise<void | T[]>

    Finally returns error as a rejected Promise if timeout is exceeded, else returns an array of values for each Promise in promises

      • <T>(promises: Promise<T>[]): Promise<void | T[]>
      • Type parameters

        • T

        Parameters

        • promises: Promise<T>[]

        Returns Promise<void | T[]>

String Functions

Const camelCase

  • camelCase(value: string): string
  • Returns value in camelCase.

    memberof

    core

    since

    0.1.0

    see

    pascalCase

    example
    camelCase(''); //=> ''
    camelCase('foo'); //=> 'foo'
    camelCase('fooBar'); //=> 'fooBar'
    camelCase('FOO'); //=> 'foo'
    camelCase('foo bar'); //=> 'fooBar'
    camelCase('fooBarBazQUX'); //=> 'fooBarBazQux'
    camelCase('FooBar'); //=> 'fooBar'
    camelCase('--foo-bar'); //=> 'fooBar'
    camelCase('__FOO_BAR__'); //=> 'fooBar'
    

    Parameters

    • value: string

      string to alter.

    Returns string

    Returns value in camelCase.

Const constantCase

  • constantCase(value: string): string
  • Returns value in 'CONSTANT_CASE'.

    memberof

    core

    since

    0.1.0

    see

    upperCase snakeCase

    example
    constantCase(''); //=> ''
    constantCase('foo'); //=> 'FOO'
    constantCase('fooBar'); //=> 'FOO_BAR'
    constantCase('FOO'); //=> 'FOO'
    constantCase('foo bar'); //=> 'FOO_BAR'
    constantCase('fooBarBazQUX'); //=> 'FOO_BAR_BAZ_QUX'
    constantCase('FooBar'); //=> 'FOO_BAR'
    constantCase('__foo_bar'); //=> 'FOO_BAR'
    constantCase('__FOO_BAR__'); //=> 'FOO_BAR'
    

    Parameters

    • value: string

      Array to test.

    Returns string

    value in 'CONSTANT_CASE'.

Const endsWith

  • endsWith(target: string): (value: string) => boolean
  • Finally returns true if 'value' starts with target, else returns false.

    memberof

    core

    since

    0.1.0

    see

    startsWith

    example
    endsWith('')(''); //=> true
    endsWith('foo')('foo bar baz'); //=> false
    endsWith('bar')('foo bar baz'); //=> false
    endsWith('baz')('foo bar baz'); //=> true
    endsWith('qux')('foo bar baz'); //=> false
    

    Parameters

    • target: string

      Target string to check for.

    Returns (value: string) => boolean

    Finally returns true if 'value' starts with target, else returns false.

      • (value: string): boolean
      • Parameters

        • value: string

          string to test.

        Returns boolean

Const hexColorToInteger

  • hexColorToInteger(value: string): number
  • Returns value as an integer if value contains a valid hexadecimal color string, else throws TypeError.

    Valid hexadecimal strings are 7 character strings beginning with #, followed by a hexadecimal number within the range of 000000 to FFFFFF beginning with a # prefix that is follwed by a 6 digit hexadecimal number, e.g., #FFFFFF).

    throws

    {TypeError} value must be a hex string.

    memberof

    core

    since

    0.1.0

    see

    integerToHexColor isHexColor

    example
     hexColorToInteger(''); //=> `TypeError`
     hexColorToInteger('foo bar'); //=> `TypeError`
     hexColorToInteger('#00000F'); //=> 15
     hexColorToInteger('foo #00000F bar'); //=> 15
    

    Parameters

    • value: string

      string to convert.

    Returns number

    value as an integer if value contains a valid hexadecimal color string.

Const initialsCase

  • initialsCase(value: string): string
  • Returns value in 'I C' (initials case).

    memberof

    core

    since

    0.1.0

    see

    titleCase

    example
    initialsCase(''); //=> ''
    initialsCase('foo'); //=> 'F'
    initialsCase('fooBar'); //=> 'F B'
    initialsCase('FOO'); //=> 'F'
    initialsCase('foo bar'); //=> 'F B'
    initialsCase('fooBarBazQUX'); //=> 'F B B Q'
    initialsCase('FooBar'); //=> 'F B'
    initialsCase('__foo_bar'); //=> 'F B'
    initialsCase('__FOO_BAR__'); //=> 'F B'
    

    Parameters

    • value: string

      string to alter.

    Returns string

    value in 'I C' (initials case).

Const invertHexColor

  • invertHexColor(value: string): string
  • Accepts a valid hex color value & returns it's inverted valid hex color.

    memberof

    core

    since

    1.0.0

    see

    stringToHexColor isHexColor

    example
    invertHexColor() //=> Error
    invertHexColor('qux') //=> Error
    invertHexColor('#000000') //=> '#FFFFFF'
    invertHexColor('#FF0000') //=> '#FF0000'
    invertHexColor('#00FF00') //=> '#FF00FF'
    

    Parameters

    • value: string

      valid hex color string to convert to hex color.

    Returns string

    value as valid hex color.

Const isHexColor

  • isHexColor(value: string): boolean
  • Returns true if value is a color hexadecimal color string (via hexColorToInteger) where hexadecimal number is within the range of 000000 to FFFFFF.

    memberof

    core

    since

    0.1.0

    see

    hexColorToInteger

    example
     isHexColor(''); //=> false
     isHexColor('foo'); //=> false
     isHexColor('0xFFFFFF'); //=> false
     isHexColor('1'); //=> false
     isHexColor('000000'); //=> false
     isHexColor('#FFF'); //=> false
     isHexColor('#000000'); //=> true
     isHexColor('#FFFFFF'); //=> true
     isHexColor('#FF0000'); //=> true
    

    Parameters

    • value: string

      Value to test.

    Returns boolean

    true if value is a color hexadecimal color string.

Const isString

  • isString(value: any): boolean
  • Returns true if value is a string, else returns false.

    memberof

    core

    since

    0.1.0

    example
    // String values.
    isString(''); //=> true
    isString('a'); //=> false
    isString('abc'); //=> false
    
    // Non-string values.
    isString(undefined); //=> false
    isString(null); //=> false
    isString(true); //=> false
    isString(); //=> false
    isString(1); //=> false
    isString([1]); //=> false
    isString({ a: 1 }); //=> false
    

    Parameters

    • value: any

      Value to test.

    Returns boolean

    true if value is a string, else returns false.

Const joinToArray

  • joinToArray<TDelimiter>(delimiter: TDelimiter): <TArr>(arr: TArr[]) => (TDelimiter | TArr)[][]
  • Returns text as an array of numbers where each number is the incrementing number representation of letter characters where space character is considered the 0, 'a' is 1, etc. until 'z' which is 26.

    memberof

    core

    since

    1.0.0

    example
    toLetterChars(); //=> Error
    toLetterChars(''); //=> ''
    toLetterChars('foo bar 123 !"£'); //=> 'foobar'
    

    Type parameters

    • TDelimiter

    Parameters

    • delimiter: TDelimiter

    Returns <TArr>(arr: TArr[]) => (TDelimiter | TArr)[][]

    Returns a string containing letters from text.

      • <TArr>(arr: TArr[]): (TDelimiter | TArr)[][]
      • Type parameters

        • TArr

        Parameters

        • arr: TArr[]

        Returns (TDelimiter | TArr)[][]

Const kebabCase

  • kebabCase(value: string): string
  • Returns value in kebab-case.

    memberof

    core

    since

    0.1.0

    see

    snakeCase

    example
    kebabCase(''); //=> ''
    kebabCase('foo'); //=> 'foo'
    kebabCase('fooBar'); //=> 'foo-Bar'
    kebabCase('FOO'); //=> 'FOO'
    kebabCase('foo bar'); //=> 'foo-bar'
    kebabCase('fooBarBazQUX'); //=> 'foo-Bar-Baz-QUX'
    kebabCase('FooBar'); //=> 'Foo-Bar'
    kebabCase('--foo-bar'); //=> 'foo-bar'
    kebabCase('__FOO_BAR__'); //=> 'FOO-BAR'
    

    Parameters

    • value: string

      string to alter.

    Returns string

    value in kebab-case

Const lowerCase

  • lowerCase(value: string): string
  • Returns value in 'lower case'.

    memberof

    core

    since

    0.1.0

    see

    upperCase

    example
    lowerCase(''); //=> ''
    lowerCase('foo'); //=> 'foo'
    lowerCase('fooBar'); //=> 'foo bar'
    lowerCase('FOO'); //=> 'foo'
    lowerCase('foo bar'); //=> 'foo bar'
    lowerCase('fooBarBazQUX'); //=> 'foo bar baz qux'
    lowerCase('FooBar'); //=> 'foo bar'
    lowerCase('__foo_bar'); //=> 'foo bar'
    lowerCase('__FOO_BAR__'); //=> 'foo bar'
    

    Parameters

    • value: string

      Value to alter.

    Returns string

    value in 'lower case'.

Const mapWords

  • mapWords(transformer: (word: string) => string, joinDelimiter?: string): (value: string) => string
  • Finally returns a string with all words (via toWords) in value mapped to new values via transformer, and delimited by joinDelimiter.

    memberof

    core

    since

    0.1.0

    see

    map toWords

    example
    const toWordLength = word => word.length.toString();
    mapWords(toWordLength)(''); //=> ''
    mapWords(toWordLength)('a ab abc'); //=> '1 2 3'
    mapWords(toWordLength, ',')('a ab abc'); //=> '1,2,3'
    

    Parameters

    • transformer: (word: string) => string

      Returns a new word.

        • (word: string): string
        • Parameters

          • word: string

          Returns string

    • joinDelimiter: string = ' '

      string to delimit words (optional, defaults to ' ').

    Returns (value: string) => string

      • (value: string): string
      • Parameters

        • value: string

          string with words to map.

        Returns string

Const pascalCase

  • pascalCase(value: string): string
  • Returns value in PascalCase.

    memberof

    core

    since

    0.1.0

    see

    camelCase

    example
    pascalCase(''); //=> ''
    pascalCase('foo'); //=> 'Foo'
    pascalCase('fooBar'); //=> 'FooBar'
    pascalCase('FOO'); //=> 'Foo'
    pascalCase('foo bar'); //=> 'FooBar'
    pascalCase('fooBarBazQUX'); //=> 'FooBarBazQux'
    pascalCase('FooBar'); //=> 'FooBar'
    pascalCase('--foo-bar'); //=> 'FooBar'
    pascalCase('__FOO_BAR__'); //=> 'FooBar'
    

    Parameters

    • value: string

      String to alter.

    Returns string

    value in PascalCase.

Const pluralize

  • pluralize(count?: number, options?: PluralizeOptions): (value: string) => string
  • Provides basic pluralization by finally returning value if it does not need pluralization (i.e., if value is an empty string, or countis0or less, orvalueis in already in plural form according tooptions.pluralMap), else returns a pluralized form of value(i.e., suffixed with eitheroptions.pluralSuffix, or a suffix provided by options.pluralMapwhich takes priority overoptions.pluralSuffix`).

    memberof

    core

    since

    0.1.0

    example
    pluralize(1)(''); //=> ''
    pluralize()(''); //=> ''
    [-2, -1, -0].map(c => pluralize(c)('page')) //=> ['page', 'page', 'page']
    [1, 2, 3].map(c => pluralize(c)('page')) //=> ['pages', 'pages', 'pages']
    pluralize(1, { pluralSuffix: 'es' })('foo'); //=> 'fooes'
    ['foo', 'baz'].map(pluralize(1, { pluralMap: { foo: '', baz: 'es' } })) //=> ['foo', 'bazes']
    pluralize(1, { pluralSuffix: 'SUFFIX' pluralMap: { foo: 'MAP' } })('foo'); //=> 'fooMAP'
    

    Parameters

    • count: number = 0

      Integer indicating whether to pluralize (optional, defaults to 0, pluralizes if count is 1 or greater, else returns unchanged value)

    • options: PluralizeOptions = {}

    Returns (value: string) => string

    Finally returns a string containing value in its pluralized form.

      • (value: string): string
      • Parameters

        • value: string

        Returns string

Const pluralizeWords

  • pluralizeWords(countMap?: Record<string, number>, joinDelimiter?: string): (value: string) => string
  • Finally returns a string containing all words (via toWords) in value in their pluralized form (via pluralize) & delimited by joinDelimiter (optional, defaults to ' ').

    memberof

    core

    since

    0.1.0

    see

    mapWords pluralize toWords

    example
    pluralizeWords({ foo: 1 })(''); //=> ''
    [-2, -1, 0].map(c => pluralizeWords({ foo: c, bar: c, baz: c })('foo bar baz'); //=> 'foo bar baz'
    [1, 2, 3].map(c => pluralizeWords({ foo: c, bar: c, baz: c })('foo bar baz'); //=> 'foos bars bazs'
    pluralizeWords({ foo: 1 }, ',')('foo bar baz'); //=> 'foos,bar,baz'
    

    Parameters

    • countMap: Record<string, number> = {}

      Object mapping words to their count where count is an integer indicating whether to pluralize the word

    • joinDelimiter: string = ' '

      A string to delimit words in the returned string (optional, defaults to ''). pluralizeWordsd form (takes priority over options.pluralSuffix).

    Returns (value: string) => string

    Finally returns a string containing value with all words in their pluralized form.

      • (value: string): string
      • Parameters

        • value: string

        Returns string

Const randomHexColor

  • randomHexColor(value?: string, ignoredHexColors?: IgnoredHexColors): string
  • Returns a valid hexadecimal color string from value where all color chunks are randomly generated (unless ignored via optional IgnoredHexColors which will have their color chunks equal to those in value).

    memberof

    core

    since

    0.1.0

    see

    isHexColor

    example
     randomHexColor(); //=> #vvvvvv where v is a random hexadecimal digit
     randomHexColor('#000000'); //=> #vvvvvv where v is a random hexadecimal digit
     randomHexColor('#000000', { red: true }); //=> #00vvvv where v is a random hexadecimal digit
     randomHexColor('#111111', { red: true }); //=> #110000 where where v is a hexadecimal digit
     randomHexColor('#000000', { red: true, green: true }); //=> #0000vv where where v is a random hexadecimal digit
     randomHexColor('#000000', { red: true, green: true, blue: true }); //=> #000000 where where v is a random hexadecimal digit
    

    Parameters

    • value: string = ...

      A string containing a valid hexadecimal color string to randomize (optional, defaults to #000000 which is also the default for a value with an invalid hexadecimal color string).

    • ignoredHexColors: IgnoredHexColors = {}

      An object indicating which color chunks of a hexadecimal color string should not be randomised (optional, defaults to {}).

    Returns string

    A string containing a valid hexadecimal color string where all color chunks are randomized unless ignored via IgnoredHexColors.

Const repeat

  • repeat(count: number): (value: string) => string
  • Finally returns value repeated count times.

    memberof

    core

    since

    0.1.0

    example
    repeat(4)(''); //=> ''
    repeat(4)('a'); //=> 'aaaa'
    repeat(4)('foo '); //=> 'foo foo foo foo '
    repeat(0)('foo'); //=> ''
    repeat(-1)('foo'); //=> ''
    

    Parameters

    • count: number

      Positive integer indicating the number of times value is repeated (defaults to 0 if negative).

    Returns (value: string) => string

    Finally returns a string containing value repeated count times.

      • (value: string): string
      • Parameters

        • value: string

        Returns string

Const replaceAll

  • replaceAll(find: string, replace?: string): (value: string) => string
  • Finally returns value with all matching occurances of find replaced with replace.

    memberof

    core

    since

    0.1.0

    see

    replaceFirst

    example
    replaceAll('bar', 'qux')(''); //=> ''
    replaceAll('bar')('foo bar baz bar'); //=> 'foo  baz '
    replaceAll('bar', 'qux')('foo bar baz bar'); //=> 'foo qux baz qux'
    

    Parameters

    • find: string

      string to replace.

    • replace: string = ''

      string to replace find with.

    Returns (value: string) => string

    Finally returns value with all matching occurances of find replaced with replace.

      • (value: string): string
      • Parameters

        • value: string

          string to search & replace in.

        Returns string

Const replaceFirst

  • replaceFirst(find: string, replace?: string): (value: string) => string
  • Finally returns value with the first matching occurance of find replaced with replace.

    memberof

    core

    since

    0.1.0

    see

    replaceAll

    example
    replaceFirst('bar', 'qux')(''); //=> ''
    replaceFirst('bar')('foo bar baz bar'); //=> 'foo  baz bar'
    replaceFirst('bar', 'qux')('foo bar baz bar'); //=> 'foo qux baz bar'
    

    Parameters

    • find: string

      string to replace.

    • replace: string = ''

      string to replace find with.

    Returns (value: string) => string

    Finally returns value with the first matching occurance of find replaced with replace.

      • (value: string): string
      • Parameters

        • value: string

          string to search & replace in.

        Returns string

Const sentenceCase

  • sentenceCase(value: string): string
  • Returns value in 'Sentence case'.

    memberof

    core

    since

    0.1.0

    see

    titleCase

    example
    sentenceCase(''); //=> ''
    sentenceCase('foo'); //=> 'Foo'
    sentenceCase('fooBar'); //=> 'Foo bar'
    sentenceCase('FOO'); //=> 'Foo'
    sentenceCase('foo bar'); //=> 'Foo bar'
    sentenceCase('fooBarBazQUX'); //=> 'Foo bar baz qux'
    sentenceCase('FooBar'); //=> 'Foo bar'
    sentenceCase('__foo_bar'); //=> 'Foo bar'
    sentenceCase('__FOO_BAR__'); //=> 'Foo bar'
    

    Parameters

    • value: string

      string to alter.

    Returns string

    value in 'Sentence case'.

Const snakeCase

  • snakeCase(value: string): string
  • Returns value in snake_case.

    memberof

    core

    since

    0.1.0

    see

    snakeCase

    example
    snakeCase(''); //=> ''
    snakeCase('foo'); //=> 'foo'
    snakeCase('fooBar'); //=> 'foo_Bar'
    snakeCase('FOO'); //=> 'FOO'
    snakeCase('foo bar'); //=> 'foo_bar'
    snakeCase('fooBarBazQUX'); //=> 'foo_Bar_Baz_QUX'
    snakeCase('FooBar'); //=> 'Foo_Bar'
    snakeCase('__foo_bar'); //=> 'foo_bar'
    snakeCase('__FOO_BAR__'); //=> 'FOO_BAR'
    

    Parameters

    • value: string

      string to alter.

    Returns string

    value in snake_case.

Const split

  • split(delimiter?: string | RegExp, limit?: number): (value: string) => string[]
  • Finally returns an array containing a total of limit strings from value that were previously delimited by delimiter.

    memberof

    core

    since

    0.1.0

    example
    split('')(''); //=> []
    split()('foo bar baz'); //=> ['foo bar baz']
    split('qux')('foo bar baz'); //=> ['foo bar baz']
    split('')('foo'); //=> ['f', 'o', 'o']
    split(' ', 2)('foo bar baz'); //=> ['foo', 'bar']
    

    Parameters

    • Optional delimiter: string | RegExp
    • Optional limit: number

    Returns (value: string) => string[]

    Finally returns an array containing a total of limit strings from value that were previously delimited by delimiter.

      • (value: string): string[]
      • Parameters

        • value: string

        Returns string[]

Const startsWith

  • startsWith(target: string): (value: string) => boolean
  • Returns true if 'value' starts with target, else returns false.

    memberof

    core

    since

    0.1.0

    example
    startsWith('')(''); //=> true
    startsWith('foo')('foo bar baz'); //=> true
    startsWith('bar')('foo bar baz'); //=> false
    startsWith('baz')('foo bar baz'); //=> false
    startsWith('qux')('foo bar baz'); //=> false
    

    Parameters

    • target: string

      string to search for.

    Returns (value: string) => boolean

    true if 'value' starts with target, else returns false.

      • (value: string): boolean
      • Parameters

        • value: string

          string to search in.

        Returns boolean

Const stringCount

  • stringCount(value: string): number
  • Returns the number of characters in value.

    memberof

    core

    since

    0.1.0

    see

    count

    example
    stringCount(''); //=> 0
    stringCount('abc'); //=> 3
    

    Parameters

    • value: string

      string to test.

    Returns number

    number of characters in value

Const stringCountIs

  • stringCountIs(count: number): (value: string) => boolean
  • Finally returns true if values's total characters equals count, else returns false.

    memberof

    core

    since

    0.1.0

    see

    countIs stringCount

    example
    stringCountIs(0)(''); //=> true
    stringCountIs(3)('abc'); //=> true
    

    Parameters

    • count: number

      The expected count.

    Returns (value: string) => boolean

    Finally returns true if values's total characters equals count, else returns false.

      • (value: string): boolean
      • Parameters

        • value: string

          string to test.

        Returns boolean

Const stringCountIsAny

  • stringCountIsAny(value: string): boolean
  • Returns true if values's total characters is greater than 0, else returns false.

    memberof

    core

    since

    0.1.0

    see

    countIsAny stringCount stringCountIs

    example
    stringCountIsAny(0)(''); //=> false
    stringCountIsAny(3)('abc'); //=> true
    

    Parameters

    • value: string

      string to test.

    Returns boolean

    true if values's total characters is greater than 0, else returns false.

Const stringCountIsNone

  • stringCountIsNone(value: string): boolean
  • Returns true if values's total characters is 0, else returns false.

    memberof

    core

    since

    0.1.0

    see

    countIsNone stringCount stringCountIsNone

    example
    stringCountIsNone(0)(''); //=> true
    stringCountIsNone(3)('abc'); //=> false
    

    Parameters

    • value: string

      string to test.

    Returns boolean

    true if values's total characters is 0, else returns false.

Const stringEquals

  • stringEquals(value1: string): (value2: string) => boolean
  • Finally returns true if the literal string values of value1 & value2 are equal, else returns false.

    memberof

    core

    since

    0.1.0

    see

    equals

    example
    stringEquals('')(''); //=> true
    stringEquals('foo bar')('foo bar'); //=> true
    stringEquals('foo bar')('foo baz'); //=> false
    

    Parameters

    • value1: string

      First value to test.

    Returns (value2: string) => boolean

    Finally returns true if the literal string values of value1 & value2 are equal, else returns false.

      • (value2: string): boolean
      • Parameters

        • value2: string

          Second value to test.

        Returns boolean

Const stringExcludes

  • stringExcludes(...elements: any[]): (value: string) => boolean
  • Inverse of stringIncludes (i.e., finally returns true if value does not include all elements, else returns false).

    memberof

    core

    since

    0.1.0

    see

    excludes stringIncludes

    example
    stringExcludes('foo')('') //=> true
    stringExcludes('foo')('foo bar baz') //=> false
    stringExcludes('qux')('foo bar baz') //=> true
    stringExcludes('foo', 'bar')('foo bar baz') //=> false
    

    Parameters

    • Rest ...elements: any[]

      Elements to check for.

    Returns (value: string) => boolean

    Finally returns true if value does not include all elements, else returns false

      • (value: string): boolean
      • Parameters

        • value: string

          string to test.

        Returns boolean

Const stringHead

  • stringHead(value: string): string
  • Returns the first character of value.

    memberof

    core

    since

    0.1.0

    see

    head

    example
    stringHead(''); //=> ''
    stringHead('foo'); //=> 'F'
    stringHead('foo bar'); //=> 'F'
    

    Parameters

    • value: string

      string to use.

    Returns string

    The first character of value

Const stringIf

  • stringIf(predicate: (value: string) => boolean, defaultValue?: string): (value: string) => string
  • Finally returns value if predicate returns true, else returns defaultValue.

    memberof

    core

    since

    0.1.0

    example
    stringIf(() => true, 'foo')('abc'); //=> 'abc'
    stringIf(() => false, 'foo')('abc'); //=> 'foo'
    

    Parameters

    • predicate: (value: string) => boolean

      Returns true to indicate value should finally be returned, else returns false to indicate defaultValue should be returned.

        • (value: string): boolean
        • Parameters

          • value: string

          Returns boolean

    • defaultValue: string = ''

      Value to return if predicate returns false (optional, defaults to empty string).

    Returns (value: string) => string

    Finally returns value if predicate returns true, else returns defaultValue.

      • (value: string): string
      • Parameters

        • value: string

        Returns string

Const stringIncludes

  • stringIncludes(...elements: any[]): (value: string) => boolean
  • Finally returns true if value includes all elements, else returns false.

    memberof

    core

    since

    0.1.0

    see

    includes

    example
    stringIncludes('foo')('') //=> false
    stringIncludes('qux')('foo bar baz') //=> false
    stringIncludes('foo')('foo bar baz') //=> true
    stringIncludes('foo', 'bar')('foo bar baz') //=> true
    stringIncludes('foo', 'qux')('foo bar baz') //=> true
    

    Parameters

    • Rest ...elements: any[]

      Elements to check for.

    Returns (value: string) => boolean

    Finally returns true if value includes all elements, else returns false.

      • (value: string): boolean
      • Parameters

        • value: string

          string to use.

        Returns boolean

Const stringIncludesLower

  • stringIncludesLower(...elements: string[]): (value: string) => boolean
  • Similar to stringIncludes but treats elements and value as lowercase. I.e., finally returns true if value includes all elements (where value and elements are always treated as lowercase), else returns false.

    memberof

    core

    since

    0.1.0

    see

    lowerCase stringIncludes

    example
    stringIncludesLower('foo')('') //=> false
    stringIncludesLower('qux')('foo bar baz') //=> false
    stringIncludesLower('foo', 'bar')('foo bar baz') //=> true
    stringIncludesLower('FOO', 'BAR')('foo bar baz') //=> true
    

    Parameters

    • Rest ...elements: string[]

      Elements to check for.

    Returns (value: string) => boolean

    finally returns true if value includes all elements, else returns false

      • (value: string): boolean
      • Parameters

        • value: string

          string to use.

        Returns boolean

Const stringOr

  • stringOr(defaultValue?: string): (value: any) => string
  • Finally returns value if it is valid via isString, else returns defaultValue.

    memberof

    core

    since

    0.1.0

    see

    isString valueIf

    example
    stringOr('foo')(); //=> 'foo'
    stringOr('foo')(1); //=> 'foo'
    stringOr('foo')('bar'); //=> 'bar'
    

    Parameters

    • defaultValue: string = ''

    Returns (value: any) => string

    Finally returns value if it is valid via isString, else returns defaultValue.

      • (value: any): string
      • Parameters

        • value: any

          Value to test.

        Returns string

Const stringToArray

  • stringToArray<TValue>(value?: string, defaultValue?: TValue[]): any
  • Convenience method similar to stringToObject but focuses on arrays, i.e., finally returns value as an array if value is a valid JSON string, else returns defaultValue.

    memberof

    core

    since

    1.0.0

    see

    stringToObject

    example
    stringToArray('') //=> []
    stringToArray('foo') //=> []
    stringToArray('foo', [4]) //=> [4]
    stringToArray([1, 2, 3]) //=> [1, 2, 3]
    

    Type parameters

    • TValue

    Parameters

    • value: string = ''

      string to convert to an array (optional, defaults to '').

    • defaultValue: TValue[] = []

      array to return if value is not a valid JSON string (optional, defaults to []).

    Returns any

    value as an array.

Const stringToCharCodes

  • stringToCharCodes(value: string): number[]
  • Returns value as an array of character codes.

    memberof

    core

    since

    1.0.0

    see

    stringToArray

    example
    stringToCharCodes() //=> Error
    stringToCharCodes('') //=> []
    stringToCharCodes('foo bar') //=> [102, 111, 111, 32, 98, 97, 114]
    

    Parameters

    • value: string

      string to convert to an array (optional, defaults to '').

    Returns number[]

    value as an array of character codes.

Const stringToHash

  • stringToHash(value: string): number
  • Returns value as a positive hash number.

    Useful for converting strings to pseudo-unique IDs that attempt to be unique to the string but there is a possibility of an ID being shared by multiple strings.

    memberof

    core

    since

    1.0.0

    see

    stringToCharCodes

    example
    stringToCharCodes() //=> Error
    stringToCharCodes('') //=> 0
    stringToCharCodes('foo bar') //=> 682507847
    

    Parameters

    • value: string

      string to convert to hash.

    Returns number

    value as a positive hash number.

Const stringToHex

  • stringToHex(value: string): string
  • Returns value as a string hexadecimal representation of character codes.

    memberof

    core

    since

    1.0.0

    see

    stringToCharCodes

    example
    stringToCharCodes() //=> Error
    stringToCharCodes('') //=> ''
    stringToCharCodes('foo bar') //=> '666F6F20626172'
    

    Parameters

    • value: string

      string to convert to hex.

    Returns string

    value as a string hexadecimal representation of character codes.

Const stringToHexColor

  • stringToHexColor(value: string): string
  • Returns value as a valid hex color (i.e., a positive 6 digit hexadecimal prepended by '#' where any letters are uppercase).

    Useful for converting strings to pseudo-unique IDs that attempt to be unique to the string but there is a possibility of an ID being shared by multiple strings.

    memberof

    core

    since

    1.0.0

    see

    stringToHex stringToHash

    example
    stringToCharCodes() //=> Error
    stringToCharCodes('') //=> #000000
    stringToCharCodes('foo bar') //=> #28AE3E
    

    Parameters

    • value: string

      string to convert to hex color.

    Returns string

    value as valid hex color.

Const stringToObject

  • stringToObject<TValue>(value?: string, defaultValue?: Record<string, TValue>): any
  • Inverse of objectToString, i.e., finally returns value as an object if value is a valid JSON string, else returns defaultValue.

    memberof

    core

    since

    0.1.0

    see

    objectToString

    example
    stringToObject('') //=> {}
    stringToObject('foo') //=> {}
    stringToObject('foo', { d: 4 }) //=> { d: 4 }
    stringToObject({"a":1,"b":"2","c":3}) //=> { a: 1, b: '2', c: 3 }
    

    Type parameters

    • TValue

    Parameters

    • value: string = ''

      string to convert to object (optional, defaults to '').

    • defaultValue: Record<string, TValue> = {}

      object to return if value is not a valid JSON string (optional, defaults to {}).

    Returns any

    value as an object.

Const stringWrap

  • stringWrap(wrapper: string): (value: string) => string
  • Finally returns value with wrapper prepended & appended.

    memberof

    core

    since

    0.1.0

    example
    stringWrap('"')('') //=> '""'
    stringWrap('"')('foo bar baz') //=> "foo bar baz"
    

    Parameters

    • wrapper: string

      string to wrap value with.

    Returns (value: string) => string

    Finally returns value with wrapper prepended & appended.

      • (value: string): string
      • Parameters

        • value: string

          string to wrap.

        Returns string

Const titleCase

  • titleCase(value: string): string
  • Returns value in 'Title Case'.

    memberof

    core

    since

    0.1.0

    see

    pascalCase sentenceCase

    example
    titleCase(''); //=> ''
    titleCase('foo'); //=> 'Foo'
    titleCase('fooBar'); //=> 'Foo Bar'
    titleCase('FOO'); //=> 'Foo'
    titleCase('foo bar'); //=> 'Foo Bar'
    titleCase('fooBarBazQUX'); //=> 'Foo Bar Baz Qux'
    titleCase('FooBar'); //=> 'Foo Bar'
    titleCase('__foo_bar'); //=> 'Foo Bar'
    titleCase('__FOO_BAR__'); //=> 'Foo Bar'
    

    Parameters

    • value: string

      string to alter.

    Returns string

    value in 'Title Case'.

Const toDigitChars

  • toDigitChars(text: string): string
  • Returns a string containing digit characters (i.e., 0-9) in text.

    memberof

    core

    since

    1.0.0

    example
    toDigitChars(); //=> Error
    toDigitChars(''); //=> ''
    toDigitChars('foo bar 0123.456,789 !"£'); //=> '0123456789'
    

    Parameters

    • text: string

      string to return letters for.

    Returns string

    Returns a string containing digits from text.

Const toLetterChars

  • toLetterChars(text: string, keepSpacing?: boolean): string
  • Returns a string containing letter characters (i.e., a-z with casing preserved) in text.

    Spacing (excluding leading/trailing space characters, which are always removed) can be optionally kept when keepSpacing is true, else all space characters are removed.

    memberof

    core

    since

    1.0.0

    example
    toLetterChars(); //=> Error
    toLetterChars(''); //=> ''
    toLetterChars(' foo bar  qux 123 !"£ '); //=> 'foobarqux'
    
    // Keep spacing.
    toLetterChars(' foo bar  qux 123 !"£ ', true); //=> 'foo bar qux'
    

    Parameters

    • text: string

      string to return letters for.

    • keepSpacing: boolean = false

      Whether to keep spacing in returned string (optional, defaults to false).

    Returns string

    Returns a string containing letters from text.

Const toLetterNumbers

  • toLetterNumbers(text: string): string
  • Returns text as an array of numbers where each number is the incrementing number representation of letter characters where space character is considered the 0, 'a' is 1, etc. until 'z' which is 26.

    memberof

    core

    since

    1.0.0

    example
    toLetterChars(); //=> Error
    toLetterChars(''); //=> ''
    toLetterChars('foo bar 123 !"£'); //=> 'foobar'
    

    Parameters

    • text: string

      string to return letters for.

    Returns string

    Returns a string containing letters from text.

Const toWords

  • toWords(wordRegex?: RegExp): (text: string) => string[]
  • Finally returns an array of strings matching wordRegex.

    memberof

    core

    since

    0.1.0

    example
    toWords(''); //=> []
    toWords('F Foo foo fooBarBazQUX'); //=> ['F', 'Foo', 'foo', 'foo', 'Bar', 'Baz', 'QUX'],
    

    Parameters

    • wordRegex: RegExp = ...

      Regular expression to detect words (optional, defaults to omit non-alphanumeric characters before extracting space-delimited strings, letters, numbers, and toWords within special cases like camelCase, etc.).

    Returns (text: string) => string[]

    Finally returns an array of strings matching wordRegex.

      • (text: string): string[]
      • Parameters

        • text: string

          string to alter.

        Returns string[]

Const trim

  • trim(value: string): string
  • Returns value without leading or trailing spaces.

    memberof

    core

    since

    0.1.0

    example
    trim(''); //=> ''
    trim(' '); //=> ''
    trim('abc'); //=> 'abc'
    trim(' abc '); //=> 'abc'
    

    Parameters

    • value: string

      string to trim.

    Returns string

    value` without leading or trailing spaces.

Const truncate

  • truncate(options?: TruncateOptions): (value: string) => string
  • Finally returns value truncated based on optional TruncateOptions.

    memberof

    core

    since

    0.1.0

    see

    slice

    example
    truncate({ length: 4 })(''); //=> '...'
    const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vestibulum convallis viverra fusce.';
    truncate()(text); //=> 'Lorem ipsum dolor sit amet,...'
    truncate({ length: 10 })(text); //=> 'Lorem i...'
    truncate({ from: 'dolor' })(text); //=> 'Lorem ipsum ...'
    truncate({ trailing: '[omitted]' })(); //=> 'Lorem ipsum dolor sit[omitted]'
    

    Parameters

    • options: TruncateOptions = {}

    Returns (value: string) => string

    Finally returns value truncated based on optional TruncateOptions.

      • (value: string): string
      • Parameters

        • value: string

        Returns string

Const upperCase

  • upperCase(value: string): string
  • Returns value in 'UPPER CASE'.

    memberof

    core

    since

    0.1.0

    see

    lowerCase

    example
    upperCase(''); //=> ''
    upperCase('foo'); //=> 'FOO'
    upperCase('fooBar'); //=> 'FOO BAR'
    upperCase('FOO'); //=> 'FOO'
    upperCase('foo bar'); //=> 'FOO BAR'
    upperCase('fooBarBazQUX'); //=> 'FOO BAR BAZ QUX'
    upperCase('FooBar'); //=> 'FOO BAR'
    upperCase('__foo_bar'); //=> 'FOO BAR'
    upperCase('__FOO_BAR__'); //=> 'FOO BAR'
    

    Parameters

    • value: string

      Value to alter.

    Returns string

    value in 'UPPER CASE'.