New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

swiss-ak

Package Overview
Dependencies
Maintainers
1
Versions
70
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

swiss-ak

A collection of useful little things that I like to reuse across projects

  • 2.12.3
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

swiss-ak (Swiss Army Knife)

A collection of useful little things that I like to reuse across projects

times

A collection of Tools for calculating simple times. Each unit (e.g. second) has: a type (second), a constant (SECOND) and a function for getting multiples (seconds(x: second) => ms)

unittypeconstantfunction
millisecondmsMILLISECONDmilliseconds(x: ms) => ms
secondsecondSECONDseconds(x: second) => ms
minuteminuteMINUTEminutes(x: minute) => ms
hourhourHOURhours(x: hour) => ms
daydayDAYdays(x: day) => ms
weekweekWEEKweeks(x: week) => ms
monthmonthMONTHmonths(x: month) => ms
yearyearYEARyears(x: year) => ms
decadedecadeDECADEdecades(x: decade) => ms
centurycenturyCENTURYcenturies(x: century) => ms
millenniummillenniumMILLENNIUMmillenniums(x: millennium) => ms

[↑ Back to top ↑]

waiters

Async functions that return promises at or after a given time.

'Accurate/pinged' waiters ping at intermediary points to resolve at a more accurate time.

NameDescriptionExample
waitStandard wait promise (using setTimeout)minutes(2) = in 2 minutes
waitForAccurate (pinged) wait the given msminutes(2) = in 2 minutes
waitUntilAccurate (pinged) wait until given timeDate.now() + minutes(2) = in 2 minutes
waitEveryAccurate (pinged) wait for next 'every X' eventhours(1) = next full hour (e.g. 17:00, 22:00)
intervalAccurate (pinged) interval for every 'every X' eventhours(1) = every hour, on the hour

[↑ Back to top ↑]

wait

wait(time: ms): Promise<unknown>
waiters.wait(time: ms): Promise<unknown>

Standard wait promise (using setTimeout)

import { wait } from 'swiss-ak';

console.log(new Date().toTimeString()); // 12:30:10
await wait(minutes(2));
console.log(new Date().toTimeString()); // 12:32:10
#Parameter NameRequiredType
0timeYesms
Return Type
Promise<unknown>

[↑ Back to waiters ↑]

waitUntil

waitUntil(time: ms): Promise<null>
waiters.waitUntil(time: ms): Promise<null>

Accurate (pinged) wait until given time

import { waitUntil } from 'swiss-ak';

console.log(new Date().toTimeString()); // 12:30:10
await waitUntil(Date.now() + minutes(10));
console.log(new Date().toTimeString()); // 12:40:10
#Parameter NameRequiredType
0timeYesms
Return Type
Promise<null>

[↑ Back to waiters ↑]

waitFor

waitFor(time: ms): Promise<null>
waiters.waitFor(time: ms): Promise<null>

Accurate (pinged) wait the given ms

import { waitFor } from 'swiss-ak';

console.log(new Date().toTimeString()); // 12:30:10
await waitFor(minutes(5));
console.log(new Date().toTimeString()); // 12:35:10
#Parameter NameRequiredType
0timeYesms
Return Type
Promise<null>

[↑ Back to waiters ↑]

waitEvery

waitEvery(timing: ms, offset: ms): Promise<null>
waiters.waitEvery(timing: ms, offset: ms): Promise<null>

Accurate (pinged) wait for next 'every X' event

import { waitEvery } from 'swiss-ak';

console.log(new Date().toTimeString()); // 12:30:10
await waitEvery(hours(2));
console.log(new Date().toTimeString()); // 14:00:00
#Parameter NameRequiredType
0timingYesms
1offsetNoms
Return Type
Promise<null>

[↑ Back to waiters ↑]

stopInterval

stopInterval(intID: number): void
waiters.stopInterval(intID: number): void
import { interval, stopInterval } from 'swiss-ak';

console.log(new Date().toTimeString()); // 12:30:10
interval((intID, count) => {
  console.log(new Date().toTimeString()); // 13:00:00, 14:00:00, 15:00:00
  if (count === 3) {
    stopInterval(intID);
  }
}, hours(1));
#Parameter NameRequiredType
0intIDYesnumber
Return Type
void

[↑ Back to waiters ↑]

interval

interval(action: (intID?: number, count?: number) => any, timing: ms): number
waiters.interval(action: (intID?: number, count?: number) => any, timing: ms): number

Accurate (pinged) interval for every 'every X' event

import { interval, stopInterval } from 'swiss-ak';

console.log(new Date().toTimeString()); // 12:30:10
interval((intID, count) => {
  console.log(new Date().toTimeString()); // 13:00:00, 14:00:00, 15:00:00
  if (count === 3) {
    stopInterval(intID);
  }
}, hours(1));
#Parameter NameRequiredType
0actionYes(intID?: number, count?: number) => any
1timingYesms
Return Type
number

[↑ Back to waiters ↑]

fn

A collection of useful higher-order functions.

[↑ Back to top ↑]

noop

fn.noop(): void

No operation. Do nothing, return nothing.

const run = condition ? doSomething : fn.noop;
run();
Return Type
void

[↑ Back to fn ↑]

noact

fn.noact(item: T): T

No action. Returns the first argument it receives.

const items = stuff
  .map(condition ? mapSomething : fn.noact)
#Parameter NameRequiredType
0itemNoT
Return Type
T

[↑ Back to fn ↑]

result

fn.result(item: T): () => T

Returns a function that returns the first argument.

const items = stuff
  .filter(condition ? mapSomething : fn.result(true))
#Parameter NameRequiredType
0itemNoT
Return Type
() => T

[↑ Back to fn ↑]

resolve

fn.resolve(item: T): () => Promise<T>

Returns an async function that resolves to the first argument

Like fn.result, but wrapped in a Promise

#Parameter NameRequiredType
0itemNoT
Return Type
() => Promise<T>

[↑ Back to fn ↑]

reject

fn.reject(item: T): () => Promise<T>

Returns an async function that rejects with the first argument

#Parameter NameRequiredType
0itemNoT
Return Type
() => Promise<T>

[↑ Back to fn ↑]

filters

fn.filters;

Collection of functions that can be used with Array.filter

[↑ Back to fn ↑]

exists
fn.exists(item: T): boolean
fn.filters.exists(item: T): boolean
filters.exists(item: T): boolean

Returns true if item isn't null or undefined.

[null, 1, undefined, 2].filter(fn.exists); // [1, 2]
#Parameter NameRequiredType
0itemYesT
Return Type
boolean

[↑ Back to fn ↑]

isTruthy
fn.isTruthy(item: T): boolean
fn.filters.isTruthy(item: T): boolean
filters.isTruthy(item: T): boolean

Returns true if item is truthy.

[0, 1, 2].filter(fn.isTruthy); // [1, 2]
['', 'a', 'b'].filter(fn.isTruthy); // ['a', 'b']
#Parameter NameRequiredType
0itemYesT
Return Type
boolean

[↑ Back to fn ↑]

isFalsy
fn.isFalsy(item: T): boolean
fn.filters.isFalsy(item: T): boolean
filters.isFalsy(item: T): boolean

Returns true if item is falsy.

[0, 1, 2].filter(fn.isFalsy); // [0]
['', 'a', 'b'].filter(fn.isFalsy); // ['']
#Parameter NameRequiredType
0itemYesT
Return Type
boolean

[↑ Back to fn ↑]

isEmpty
fn.isEmpty(item: T[] | string): boolean
fn.filters.isEmpty(item: T[] | string): boolean
filters.isEmpty(item: T[] | string): boolean

Returns true if item's length is 0

['', 'a', 'b'].filter(fn.isEmpty); // ['']
[[], [1], [2]].filter(fn.isEmpty); // [[]]
#Parameter NameRequiredType
0itemYesT[] | string
Return Type
boolean

[↑ Back to fn ↑]

isNotEmpty
fn.isNotEmpty(item: T[] | string): boolean
fn.filters.isNotEmpty(item: T[] | string): boolean
filters.isNotEmpty(item: T[] | string): boolean

Returns true if item's length is 1 or more

['', 'a', 'b'].filter(fn.isNotEmpty); // ['a', 'b']
[[], [1], [2]].filter(fn.isNotEmpty); // [[1], [2]]
#Parameter NameRequiredType
0itemYesT[] | string
Return Type
boolean

[↑ Back to fn ↑]

isEqual
fn.isEqual(item: T): (other: T) => boolean
fn.filters.isEqual(item: T): (other: T) => boolean
filters.isEqual(item: T): (other: T) => boolean

Returns a function that returns true if the item is equal to provided value.

[0, 1, 2].filter(fn.isEqual(1)); // [1]
#Parameter NameRequiredType
0itemYesT
Return Type
(other: T) => boolean

[↑ Back to fn ↑]

isNotEqual
fn.isNotEqual(item: T): (other: T) => boolean
fn.filters.isNotEqual(item: T): (other: T) => boolean
filters.isNotEqual(item: T): (other: T) => boolean

Returns a function that returns true if the item is not equal to provided value.

[0, 1, 2].filter(fn.isNotEqual(1)); // [0, 2]
#Parameter NameRequiredType
0itemYesT
Return Type
(other: T) => boolean

[↑ Back to fn ↑]

dedupe
fn.dedupe(item: T, index: number, array: T[]): boolean
fn.filters.dedupe(item: T, index: number, array: T[]): boolean
filters.dedupe(item: T, index: number, array: T[]): boolean

Removes duplicate items from an array.

[0, 1, 2, 1, 0].filter(fn.dedupe); // [0, 1, 2]
#Parameter NameRequiredType
0itemYesT
1indexYesnumber
2arrayYesT[]
Return Type
boolean

[↑ Back to fn ↑]

dedupeMapped
fn.dedupeMapped(mapFn: (value?: T, index?: number, array?: T[]) => U): (item: T, index: number, array: T[]) => boolean
fn.filters.dedupeMapped(mapFn: (value?: T, index?: number, array?: T[]) => U): (item: T, index: number, array: T[]) => boolean
filters.dedupeMapped(mapFn: (value?: T, index?: number, array?: T[]) => U): (item: T, index: number, array: T[]) => boolean

Removes duplicate items from an array based on a mapped value.

[2, 4, 6, 8, 10, 12].filter(fn.dedupeMapped((v) => v % 3)); // [ 2, 4, 6 ] (maps to [ 2, 1, 0, 2, 1, 0 ])
#Parameter NameRequiredType
0mapFnYes(value?: T, index?: number, array?: T[]) => U
Return Type
(item: T, index: number, array: T[]) => boolean

[↑ Back to fn ↑]

maps

fn.maps;

Collection of functions that can be used with Array.map

[↑ Back to fn ↑]

toString
fn.toString(item: T): string
fn.maps.toString(item: T): string
maps.toString(item: T): string

Maps the item to a string.

[0, 1, 2].map(fn.toString); // ['0', '1', '2']
#Parameter NameRequiredType
0itemYesT
Return Type
string

[↑ Back to fn ↑]

toNumber
fn.toNumber(item: T): number
fn.maps.toNumber(item: T): number
maps.toNumber(item: T): number

Maps the item to a number.

['0', '1', '2'].map(fn.toNumber); // [0, 1, 2]
#Parameter NameRequiredType
0itemYesT
Return Type
number

[↑ Back to fn ↑]

toBool
fn.toBool(item: T): boolean
fn.maps.toBool(item: T): boolean
maps.toBool(item: T): boolean

Maps the item to a boolean.

[0, 1, 2].map(fn.toBool); // [false, true, true]
['true', 'false', '', 'text'].map(fn.toBool); // [true, false, false, true]
#Parameter NameRequiredType
0itemYesT
Return Type
boolean

[↑ Back to fn ↑]

toProp
fn.toProp(prop: string | number): (item: O) => P
fn.maps.toProp(prop: string | number): (item: O) => P
maps.toProp(prop: string | number): (item: O) => P

Maps the item to a given property of the item

[{name: 'Jack'}, {name: 'Jill'}].map(fn.toProp('name')); // ['Jack', 'Jill']
#Parameter NameRequiredType
0propYesstring | number
Return Type
(item: O) => P

[↑ Back to fn ↑]

toFixed
fn.toFixed(precision: number): (num: number) => number
fn.maps.toFixed(precision: number): (num: number) => number
maps.toFixed(precision: number): (num: number) => number

Map the items (numbers) of an array to a fixed precision.

[1.234, 5.678, 9.012].map(fn.toFixed(2)); // [1.23, 5.68, 9.01]
#Parameter NameRequiredType
0precisionYesnumber
Return Type
(num: number) => number

[↑ Back to fn ↑]

sorts

fn.sorts;

Collection of functions that can be used with Array.sort

[↑ Back to fn ↑]

asc
fn.asc(a: any, b: any): number
fn.sorts.asc(a: any, b: any): number
sorts.asc(a: any, b: any): number

Sort ascending.

[2, 4, 3, 1].sort(fn.asc); // [1, 2, 3, 4]
#Parameter NameRequiredType
0aYesany
1bYesany
Return Type
number

[↑ Back to fn ↑]

desc
fn.desc(a: any, b: any): number
fn.sorts.desc(a: any, b: any): number
sorts.desc(a: any, b: any): number

Sort descending.

[2, 4, 3, 1].sort(fn.asc); // [4, 3, 2, 1]
#Parameter NameRequiredType
0aYesany
1bYesany
Return Type
number

[↑ Back to fn ↑]

byProp
fn.byProp(propName: string | number, sortFn: SortFn<T>): SortFn<O>
fn.sorts.byProp(propName: string | number, sortFn: SortFn<T>): SortFn<O>
sorts.byProp(propName: string | number, sortFn: SortFn<T>): SortFn<O>

Sort by a given property.

const people = [{age: 2}, {age: 4}, {age: 3}, {age: 1}];
people.sort(fn.byProp('age', fn.asc)); // [{age: 1}, {age: 2}, {age: 3}, {age: 4}]
#Parameter NameRequiredTypeDefault
0propNameYesstring | number
1sortFnNoSortFn<T>asc
Return Type
SortFn<O>

[↑ Back to fn ↑]

nearestTo
fn.nearestTo(target: T): (a: any, b: any) => number
fn.sorts.nearestTo(target: T): (a: any, b: any) => number
sorts.nearestTo(target: T): (a: any, b: any) => number

Sort by the nearest value to the given value.

Values get converted to numbers before comparison.

const people = [2, 4, 3, 1];
people.sort(fn.nearestTo(3)); // [3, 2, 4, 1]
#Parameter NameRequiredType
0targetYesT
Return Type
(a: any, b: any) => number

[↑ Back to fn ↑]

furthestFrom
fn.furthestFrom(target: T): (a: any, b: any) => number
fn.sorts.furthestFrom(target: T): (a: any, b: any) => number
sorts.furthestFrom(target: T): (a: any, b: any) => number

Sort by the furthest value to the given value.

const people = [2, 4, 3, 1];
people.sort(fn.furthestFrom(3)); // [1, 2, 4, 3]
#Parameter NameRequiredType
0targetYesT
Return Type
(a: any, b: any) => number

[↑ Back to fn ↑]

array
fn.array(sortFn: SortFn<T>): (a: T[], b: T[]) => number
fn.sorts.array(sortFn: SortFn<T>): (a: T[], b: T[]) => number
sorts.array(sortFn: SortFn<T>): (a: T[], b: T[]) => number

Sort an array of arrays by the given sort function.

Sorts by the first item in the array, then the second, etc. until a non-zero result is found.

#Parameter NameRequiredTypeDefault
0sortFnNoSortFn<T>asc
Return Type
(a: T[], b: T[]) => number

[↑ Back to fn ↑]

arrayAsc
fn.arrayAsc;
fn.sorts.arrayAsc;
sorts.arrayAsc;

Sort an array of arrays in ascending order

Sorts by the first item in the array, then the second, etc. until a non-zero result is found.

[↑ Back to fn ↑]

arrayDesc
fn.arrayDesc;
fn.sorts.arrayDesc;
sorts.arrayDesc;

Sort an array of arrays in descending order

Sorts by the first item in the array, then the second, etc. until a non-zero result is found.

[↑ Back to fn ↑]

reduces

fn.reduces;

Collection of functions that can be used with Array.reduce

[↑ Back to fn ↑]

combine
fn.combine(a: T, b: T): T
fn.reduces.combine(a: T, b: T): T
reduces.combine(a: T, b: T): T

Adds or concats the items

[1, 2, 3].reduce(fn.combine); // 6
['a', 'b', 'c'].reduce(fn.combine); // 'abc'
#Parameter NameRequiredType
0aYesT
1bYesT
Return Type
T

[↑ Back to fn ↑]

combineProp
fn.combineProp(propName: string | number): (a: O | T, b: O) => T
fn.reduces.combineProp(propName: string | number): (a: O | T, b: O) => T
reduces.combineProp(propName: string | number): (a: O | T, b: O) => T

Adds or concats the given property of the items

const people = [{name: 'a', age: 1}, {name: 'b', age: 2}, {name: 'c', age: 3}];
people.reduce(fn.combineProp('age')); // 6
people.reduce(fn.combineProp('name')); // 'abc'
#Parameter NameRequiredType
0propNameYesstring | number
Return Type
(a: O | T, b: O) => T

[↑ Back to fn ↑]

mode
fn.mode(prev: T, curr: T, index: number, arr: T[]): T
fn.reduces.mode(prev: T, curr: T, index: number, arr: T[]): T
reduces.mode(prev: T, curr: T, index: number, arr: T[]): T

Returns the most common value in an array.

[1, 2, 3, 2, 1, 1].reduce(fn.mode); // 1
#Parameter NameRequiredType
0prevYesT
1currYesT
2indexYesnumber
3arrYesT[]
Return Type
T

[↑ Back to fn ↑]

modeMapped
fn.modeMapped(mapFn: (value: T, index: number, array: T[]) => U): (prev: T, curr: T, index: number, arr: T[]) => T
fn.reduces.modeMapped(mapFn: (value: T, index: number, array: T[]) => U): (prev: T, curr: T, index: number, arr: T[]) => T
reduces.modeMapped(mapFn: (value: T, index: number, array: T[]) => U): (prev: T, curr: T, index: number, arr: T[]) => T

Returns the most common value in an array, based on a given map function.

[2, 4, 6, 8, 9, 12].reduce(fn.modeMapped((v) => v % 3)); // 6 (maps to [ 2, 1, 0, 2, 0, 0 ])
#Parameter NameRequiredType
0mapFnYes(value: T, index: number, array: T[]) => U
Return Type
(prev: T, curr: T, index: number, arr: T[]) => T

[↑ Back to fn ↑]

everys

fn.everys;

Collection of functions that can be used with Array.every

[↑ Back to fn ↑]

isAllEqual
fn.isAllEqual(val: T, i: number, arr: T[]): boolean
fn.everys.isAllEqual(val: T, i: number, arr: T[]): boolean
everys.isAllEqual(val: T, i: number, arr: T[]): boolean

Returns if all the items are equal to one another.

[1, 1, 1].every(fn.isAllEqual); // true
[1, 2, 1].every(fn.isAllEqual); // false
#Parameter NameRequiredType
0valYesT
1iYesnumber
2arrYesT[]
Return Type
boolean

[↑ Back to fn ↑]

isUnique
fn.isUnique(val: T, i: number, arr: T[]): boolean
fn.everys.isUnique(val: T, i: number, arr: T[]): boolean
everys.isUnique(val: T, i: number, arr: T[]): boolean

Returns true if the item is unique in the array.

[1, 1, 1].every(fn.isUnique); // false
[1, 2, 1].every(fn.isUnique); // false
[1, 2, 3].every(fn.isUnique); // true
#Parameter NameRequiredType
0valYesT
1iYesnumber
2arrYesT[]
Return Type
boolean

[↑ Back to fn ↑]

ArrayTools

A collection of useful array functions.

[↑ Back to top ↑]

create

create(length: number, value: T): T[]
ArrayTools.create(length: number, value: T): T[]
filled(length: number, value: T): T[]
ArrayTools.filled(length: number, value: T): T[]

Create an array of the given length, where each value is the given value

#Parameter NameRequiredTypeDefault
0lengthNonumber1
1valueNoT1 as T
Return Type
T[]

[↑ Back to ArrayTools ↑]

range

range(length: number, multiplier: number, offset: number): number[]
ArrayTools.range(length: number, multiplier: number, offset: number): number[]

Returns an array of the given length, where each value is equal to it's index e.g. [0, 1, 2, ..., length]

ArrayTools.range(3);  // [0, 1, 2]
ArrayTools.range(5);  // [0, 1, 2, 3, 4]
ArrayTools.range(10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

ArrayTools.range(3, 2);  // [0, 2, 4]
ArrayTools.range(5, 2);  // [0, 2, 4, 6, 8]
ArrayTools.range(10, 10); // [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
#Parameter NameRequiredTypeDefault
0lengthNonumber1
1multiplierNonumber1
2offsetNonumber0
Return Type
number[]

[↑ Back to ArrayTools ↑]

zip

zip(...arrs: T[]): ZippedArrays<T>[]
ArrayTools.zip(...arrs: T[]): ZippedArrays<T>[]

Converts multiple arrays into an array of 'tuples' for each value at the corresponding indexes.

Limited to the length of the shortest provided array

Inspired by python's 'zip'

ArrayTools.zip([1, 2, 3, 4], ['a', 'b', 'c']); // [ [1, 'a'], [2, 'b'], [3, 'c'] ]
#Parameter NameRequiredType
0…arrsNoT[]
Return Type
ZippedArrays<T>[]

[↑ Back to ArrayTools ↑]

zipMax

zipMax(...arrs: T[]): ZippedArrays<T>[]
ArrayTools.zipMax(...arrs: T[]): ZippedArrays<T>[]

Converts multiple arrays into an array of 'tuples' for each value at the corresponding indexes.

Unlike zip, it will match the length of the longest provided array, filling in any missing values with undefined

Inspired by python's 'zip'

ArrayTools.zipMax([1, 2, 3, 4], ['a', 'b', 'c']); //[ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ], [ 4, undefined ] ]
#Parameter NameRequiredType
0…arrsNoT[]
Return Type
ZippedArrays<T>[]

[↑ Back to ArrayTools ↑]

sortByMapped

sortByMapped(arr: T[], mapFn: (value: T, index: number, array: T[]) => M, sortFn: (a: M, b: M) => number): T[]
ArrayTools.sortByMapped(arr: T[], mapFn: (value: T, index: number, array: T[]) => M, sortFn: (a: M, b: M) => number): T[]

Sort an array by a mapped form of the values, but returning the initial values

ArrayTools.sortByMapped(['2p', '3p', '1p'], (v) => Number(v.replace('p', ''))); // ['1p', '2p', '3p']
ArrayTools.sortByMapped(
  ['2p', '3p', '1p'],
  (v) => Number(v.replace('p', '')),
  (a, b) => b - a
); // ['3p', '2p', '1p']
#Parameter NameRequiredTypeDefault
0arrYesT[]
1mapFnYes(value: T, index: number, array: T[]) => M
2sortFnNo(a: M, b: M) => numberfn.asc
Return Type
T[]

[↑ Back to ArrayTools ↑]

randomise

randomise(arr: T[]): T[]
ArrayTools.randomise(arr: T[]): T[]

Returns a clone of the provided array with it's items in a random order

ArrayTools.randomise([1, 2, 3, 4, 5, 6]); // [ 5, 3, 4, 1, 2, 6 ]
ArrayTools.randomise([1, 2, 3, 4, 5, 6]); // [ 5, 1, 3, 2, 4, 6 ]
ArrayTools.randomise([1, 2, 3, 4, 5, 6]); // [ 6, 1, 4, 5, 2, 3 ]
ArrayTools.randomise([1, 2, 3, 4, 5, 6]); // [ 1, 4, 5, 2, 3, 6 ]
ArrayTools.randomise([1, 2, 3, 4, 5, 6]); // [ 2, 6, 1, 3, 4, 5 ]
#Parameter NameRequiredType
0arrYesT[]
Return Type
T[]

[↑ Back to ArrayTools ↑]

reverse

reverse(arr: T[]): T[]
ArrayTools.reverse(arr: T[]): T[]

Returns a new array with the order reversed without affecting original array

const arr1 = [1, 2, 3];
arr1            // [1, 2, 3]
arr1.reverse(); // [3, 2, 1]
arr1            // [3, 2, 1]

const arr2 = [1, 2, 3];
arr2            // [1, 2, 3]
ArrayTools.reverse(arr2);  // [3, 2, 1]
arr2            // [1, 2, 3]
#Parameter NameRequiredType
0arrYesT[]
Return Type
T[]

[↑ Back to ArrayTools ↑]

entries

entries(arr: T[]): [number, T][]
ArrayTools.entries(arr: T[]): [number, T][]

Returns array of 'tuples' of index/value pairs

const arr = ['a', 'b', 'c'];
ArrayTools.entries(arr); // [ [0, 'a'], [1, 'b'], [2, 'c'] ]

for (let [index, value] of entries(arr)) {
 console.log(index); // 0, 1, 2
 console.log(value); // 'a', 'b', 'c'
}
#Parameter NameRequiredType
0arrYesT[]
Return Type
[number, T][]

[↑ Back to ArrayTools ↑]

repeat

repeat(maxLength: number, ...items: T[]): T[]
ArrayTools.repeat(maxLength: number, ...items: T[]): T[]

Returns an array with the given items repeated

ArrayTools.repeat(5, 'a'); // [ 'a', 'a', 'a', 'a', 'a' ]
ArrayTools.repeat(5, 'a', 'b'); // [ 'a', 'b', 'a', 'b', 'a' ]
#Parameter NameRequiredType
0maxLengthYesnumber
1…itemsNoT[]
Return Type
T[]

[↑ Back to ArrayTools ↑]

roll

roll(distance: number, arr: T[]): T[]
ArrayTools.roll(distance: number, arr: T[]): T[]

'Roll' the array by a given amount so that is has a new first item. Length and contents remain the same, but the order is changed

ArrayTools.roll(1, [0, 1, 2, 3, 4, 5, 6, 7]); // [ 1, 2, 3, 4, 5, 6, 7, 0 ]
ArrayTools.roll(4, [0, 1, 2, 3, 4, 5, 6, 7]); // [ 4, 5, 6, 7, 0, 1, 2, 3 ]
#Parameter NameRequiredType
0distanceYesnumber
1arrYesT[]
Return Type
T[]

[↑ Back to ArrayTools ↑]

sortNumberedText

sortNumberedText(texts: string[], ignoreCase: boolean): string[]
ArrayTools.sortNumberedText(texts: string[], ignoreCase: boolean): string[]

Alphabetically sorts a list of strings, but keeps multi-digit numbers in numerical order (rather than alphabetical)

const names = ['name1', 'name10', 'name2', 'foo20', 'foo10', 'foo9'];
names.sort(); // [ 'foo10', 'foo20', 'foo9', 'name1', 'name10', 'name2' ]
ArrayTools.sortNumberedText(names); // [ 'foo9', 'foo10', 'foo20', 'name1', 'name2', 'name10' ]
#Parameter NameRequiredTypeDefault
0textsYesstring[]
1ignoreCaseNobooleantrue
Return Type
string[]

[↑ Back to ArrayTools ↑]

partition

partition(array: T[], partitionSize: number): T[][]
ArrayTools.partition(array: T[], partitionSize: number): T[][]

Breaks an array into smaller arrays of a given size

ArrayTools.partition([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]
#Parameter NameRequiredTypeDefault
0arrayYesT[]
1partitionSizeNonumberMath.ceil(array.length / 2)
Return Type
T[][]

[↑ Back to ArrayTools ↑]

groupObj

groupObj(array: T[], mapFn: (item: T, index: number, arr: T[]) => string | number): { [id: string]: T[]; [id: number]: T[]; }
ArrayTools.groupObj(array: T[], mapFn: (item: T, index: number, arr: T[]) => string | number): { [id: string]: T[]; [id: number]: T[]; }

Group items from an array into an object of arrays, based on a given map function.

const arr = [
  { group: 1, name: 'a' },
  { group: 2, name: 'b' },
  { group: 1, name: 'c' },
];
ArrayTools.groupObj(arr, item => item.group); // {
//   1: [ { group: 1, name: 'a' }, { group: 1, name: 'c' } ],
//   2: [ { group: 2, name: 'b' } ]
// }
#Parameter NameRequiredType
0arrayYesT[]
1mapFnYes(item: T, index: number, arr: T[]) => string | number
Return Type
{ [id: string]: T[]; [id: number]: T[]; }

[↑ Back to ArrayTools ↑]

group

group(array: T[], mapFn: (item: T, index: number, arr: T[]) => string | number): T[][]
ArrayTools.group(array: T[], mapFn: (item: T, index: number, arr: T[]) => string | number): T[][]

Group items from an array into an array of arrays, based on a given map function.

const arr = [
  { group: 1, name: 'a' },
  { group: 2, name: 'b' },
  { group: 1, name: 'c' },
];
ArrayTools.group(arr, item => item.group); // [
//   [ { group: 1, name: 'a' }, { group: 1, name: 'c' } ],
//   [ { group: 2, name: 'b' } ]
// ]
#Parameter NameRequiredType
0arrayYesT[]
1mapFnYes(item: T, index: number, arr: T[]) => string | number
Return Type
T[][]

[↑ Back to ArrayTools ↑]

findAndRemove

ArrayTools.findAndRemove(array: T[], predicate: (item: T, index: number, arr: T[]) => any, ...insertItems: T[]): T

Find the first item in an array that matches a given predicate, and remove it from the array

Note: This function mutates the provided array

#Parameter NameRequiredTypeDescription
0arrayYesT[]the array to mutate
1predicateYes(item: T, index: number, arr: T[]) => anya function that returns true/truthy if the item should be removed
2…insertItemsNoT[]items to insert in place of the removed item
Return Type
Tremoved item (undefined if not found)

[↑ Back to ArrayTools ↑]

findLastAndRemove

ArrayTools.findLastAndRemove(array: T[], predicate: (item: T, index: number, arr: T[]) => any, ...insertItems: T[]): T

Find the last item in an array that matches a given predicate, and remove it from the array

Note: This function mutates the provided array

#Parameter NameRequiredTypeDescription
0arrayYesT[]the array to mutate
1predicateYes(item: T, index: number, arr: T[]) => anya function that returns true/truthy if the item should be removed
2…insertItemsNoT[]items to insert in place of the removed item
Return Type
Tremoved item (undefined if not found)

[↑ Back to ArrayTools ↑]

filterAndRemove

ArrayTools.filterAndRemove(array: T[], predicate: (item: T, index: number, arr: T[]) => any): T[]

Find the items in an array that matches a given predicate, and remove them from the array

Note: This function mutates the provided array

#Parameter NameRequiredTypeDescription
0arrayYesT[]the array to mutate
1predicateYes(item: T, index: number, arr: T[]) => anya function that returns true/truthy if the item should be removed
Return Type
T[]removed items

[↑ Back to ArrayTools ↑]

utils

ArrayTools.utils;

Small helper functions that may help, but aren't important enough to be in ArrayTools directly

[↑ Back to ArrayTools ↑]

isNumString
ArrayTools.utils.isNumString(text: string): boolean

Returns true if the given string is a number

#Parameter NameRequiredType
0textYesstring
Return Type
boolean

[↑ Back to ArrayTools ↑]

partitionNums
ArrayTools.utils.partitionNums(ignoreCase: boolean): (name: string) => (string | number)[]

Splits a string into an array of strings and numbers

#Parameter NameRequiredType
0ignoreCaseYesboolean
Return Type
(name: string) => (string | number)[]

[↑ Back to ArrayTools ↑]

ObjectTools

A collection of functions for working with objects

[↑ Back to top ↑]

remodel

ObjectTools.remodel(obj: T, func: (entries: [string, V][]) => [string, W][]): O

Apply a function to the entries of an object

const input = {'foo': 2, 'bar': 1, 'baz': 4}
ObjectTools.remodel(input, (entries) => entries.filter(([k, v]) => v % 2 === 0)) // { foo: 2, baz: 4 }
#Parameter NameRequiredType
0objYesT
1funcYes(entries: [string, V][]) => [string, W][]
Return Type
O

[↑ Back to ObjectTools ↑]

remodelEach

ObjectTools.remodelEach(obj: T, func: (entry: [string, V], index: number, entries: [string, V][]) => [string, W]): O

Apply a function to each of the entries of an object

Note: similar to ObjectTools.map, but the function parameters are different. Prefer ObjectTools.map where possible.

const input = {'foo': 2, 'bar': 1, 'baz': 4}
ObjectTools.remodelEach(input, ([k, v]) => [k, v * 2]) // { foo: 4, bar: 2, baz: 8 }
#Parameter NameRequiredType
0objYesT
1funcYes(entry: [string, V], index: number, entries: [string, V][]) => [string, W]
Return Type
O

[↑ Back to ObjectTools ↑]

map

ObjectTools.map(obj: T, func: (key: string, value: V, index: number) => [string, W]): any

Maps the keys and values of an object in a similar way to Array.map

ObjectTools.map({a: 1, b: 2, c: 3}, (key, value) => [key, key + value]); // {a: 'a1', b: 'b2', c: 'c3'}
#Parameter NameRequiredType
0objYesT
1funcYes(key: string, value: V, index: number) => [string, W]
Return Type
any

[↑ Back to ObjectTools ↑]

mapValues

ObjectTools.mapValues(obj: T, func: (key: string, value: V, index: number) => W): any

Maps the values of an object in a similar way to Array.map

ObjectTools.map({a: 1, b: 2, c: 3}, (key, value) => key.repeat(value)); // {a: 'a', b: 'bb', c: 'ccc'}
#Parameter NameRequiredType
0objYesT
1funcYes(key: string, value: V, index: number) => W
Return Type
any

[↑ Back to ObjectTools ↑]

mapKeys

ObjectTools.mapKeys(obj: T, func: (key: string, value: V, index: number) => string): T

Maps the values of an object in a similar way to Array.map

ObjectTools.map({a: 1, b: 2, c: 3}, (key, value) => key.repeat(value)); // {a: 1, bb: 2, ccc: 3}
#Parameter NameRequiredType
0objYesT
1funcYes(key: string, value: V, index: number) => string
Return Type
T

[↑ Back to ObjectTools ↑]

filter

ObjectTools.filter(obj: T, func: (key: string, value: V, index: number) => boolean): O

Removes entries from an object based on a predicate function

ObjectTools.filter({a: 1, b: 2, c: 3}, (k, v) => v % 2 === 0) // { b: 2 }
#Parameter NameRequiredType
0objYesT
1funcYes(key: string, value: V, index: number) => boolean
Return Type
O

[↑ Back to ObjectTools ↑]

clean

ObjectTools.clean(obj: T): O

Removes properties with undefined values

ObjectTools.clean({a: 1, b: undefined, c: 3}) // { a: 1, c: 3 }
#Parameter NameRequiredType
0objYesT
Return Type
O

[↑ Back to ObjectTools ↑]

invert

ObjectTools.invert(obj: Ti): To

Inverts the keys and values of an object

ObjectTools.invert({ a: 'foo', b: 'bar' }); // { foo: 'a', bar: 'b'}
#Parameter NameRequiredType
0objYesTi
Return Type
To

[↑ Back to ObjectTools ↑]

StringTools

A collection of string utilities

[↑ Back to top ↑]

capitalise

StringTools.capitalise(input: string, forceRestToLowerCase: boolean): string

Capitalises the first letter of each word in a string

StringTools.capitalise('hello world'); // 'Hello World'
#Parameter NameRequiredTypeDefault
0inputNostring''
1forceRestToLowerCaseNobooleantrue
Return Type
string

[↑ Back to StringTools ↑]

angloise

StringTools.angloise(input: string): string

Remove accents from a string

StringTools.angloise('éèêë'); // 'eeee'
#Parameter NameRequiredType
0inputYesstring
Return Type
string

[↑ Back to StringTools ↑]

clean

StringTools.clean(input: string): string

Remove accents and non alphanumerics from a string

StringTools.clean('éèêë_--ab0'); // 'eeeeab0'
#Parameter NameRequiredTypeDefault
0inputNostring''
Return Type
string

[↑ Back to StringTools ↑]

repeat

StringTools.repeat(maxLength: number, repeated: string): string

Repeat the given string n times

StringTools.repeat(5, '-') // '-----'
StringTools.repeat(1, '-') // '-'
StringTools.repeat(0, '-') // ''
StringTools.repeat(-1, '-') // ''
#Parameter NameRequiredType
0maxLengthYesnumber
1repeatedYesstring
Return Type
string

[↑ Back to StringTools ↑]

makeRegExpSafe

StringTools.makeRegExpSafe(text: string): string

Makes a string safe to use in a RegExp

const textWithSpecChars = '$^*+?.()|{}[]\\';
const longText = `A long line with ${textWithSpecChars} in it`; // 'A long line with $^*+?.()|{}[]\ in it'

const safeText = makeRegExpSafe(textWithSpecChars); // '\$\^\*\+\?\.\(\)\|\{\}\[\]\\'
const regex = new RegExp(safeText);
longText.replace(regex, 'foobar'); // 'A long line with foobar in it'

longText.replace(new RegExp(makeRegExpSafe(textWithSpecChars)), 'foobar'); // 'A long line with foobar in it'
#Parameter NameRequiredType
0textYesstring
Return Type
string

[↑ Back to StringTools ↑]

replaceAll

StringTools.replaceAll(text: string, searchValue: string | RegExp, replacer: string | ((substring: string, ...args: any[]) => string)): string

'Polyfill' replacement for String.prototype.replaceAll, but uses String.prototype.replace (better backwards compatibility)

Accepts a string or RegExp as the searchValue, and a string or function as the replacer.

const input = 'the quick brown fox jumps over the lazy dog';

StringTools.replaceAll(input, /A|E|I|O|U/i, (match) => match.toUpperCase()) // 'thE qUIck brOwn fOx jUmps OvEr thE lAzy dOg'
StringTools.replaceAll(input, /A|E|I|O|U/i, '#') // 'th# q##ck br#wn f#x j#mps #v#r th# l#zy d#g'
StringTools.replaceAll(input, 'o', (match) => match.toUpperCase()) // 'the quick brOwn fOx jumps Over the lazy dOg'
StringTools.replaceAll(input, 'o', '#') // 'the quick br#wn f#x jumps #ver the lazy d#g'
#Parameter NameRequiredType
0textYesstring
1searchValueYesstring | RegExp
2replacerYesstring | ((substring: string, ...args: any[]) => string)
Return Type
string

[↑ Back to StringTools ↑]

clx

clx(...args: ClxType[]): string
StringTools.clx(...args: ClxType[]): string

Composes a className from a list of strings, conditional objects and arrays.

Accepts the different ways of supplying classes in AngularJS (ng-class) and returns a single string (so suitable for React).

clx('hello') // 'hello'
clx('foo', 'bar') // 'foo bar'
clx('foo', conditionA && 'bar') // 'foo'
clx('abc', conditionB && 'def') // 'abc def'
clx({'lorem': conditionA, 'ipsum': conditionB}) // 'ipsum'
#Parameter NameRequiredType
0…argsNoClxType[]
Return Type
string

[↑ Back to StringTools ↑]

Case Manipulators

toCamelCase
StringTools.toCamelCase(input: string | string[], capitaliseFirst: boolean): string
StringTools.fromSlugCase.toCamelCase(input: string | string[], capitaliseFirst: boolean): string
StringTools.fromSnakeCase.toCamelCase(input: string | string[], capitaliseFirst: boolean): string
StringTools.fromSpaced.toCamelCase(input: string | string[], capitaliseFirst: boolean): string
StringTools.fromCamelCase.toCamelCase(input: string | string[], capitaliseFirst: boolean): string

Convert a string to camel case (e.g. thisIsCamelCase)

#Parameter NameRequiredTypeDefault
0inputYesstring | string[]
1capitaliseFirstNobooleanfalse
Return Type
string

[↑ Back to StringTools ↑]

toLowerCamelCase
StringTools.toLowerCamelCase(input: string | string[]): string
StringTools.fromSlugCase.toLowerCamelCase(input: string | string[]): string
StringTools.fromSnakeCase.toLowerCamelCase(input: string | string[]): string
StringTools.fromSpaced.toLowerCamelCase(input: string | string[]): string
StringTools.fromCamelCase.toLowerCamelCase(input: string | string[]): string

Convert a string to lower camel case (e.g. thisIsLowerCamelCase)

#Parameter NameRequiredType
0inputYesstring | string[]
Return Type
string

[↑ Back to StringTools ↑]

toUpperCamelCase
StringTools.toUpperCamelCase(input: string | string[]): string
StringTools.fromSlugCase.toUpperCamelCase(input: string | string[]): string
StringTools.fromSnakeCase.toUpperCamelCase(input: string | string[]): string
StringTools.fromSpaced.toUpperCamelCase(input: string | string[]): string
StringTools.fromCamelCase.toUpperCamelCase(input: string | string[]): string

Convert a string to upper camel case (e.g. ThisIsLowerCamelCase)

#Parameter NameRequiredType
0inputYesstring | string[]
Return Type
string

[↑ Back to StringTools ↑]

toCharacterSeparated
StringTools.toCharacterSeparated(input: string | string[], char: string, toUpper: boolean): string
StringTools.fromSlugCase.toCharacterSeparated(input: string | string[], char: string, toUpper: boolean): string
StringTools.fromSnakeCase.toCharacterSeparated(input: string | string[], char: string, toUpper: boolean): string
StringTools.fromSpaced.toCharacterSeparated(input: string | string[], char: string, toUpper: boolean): string
StringTools.fromCamelCase.toCharacterSeparated(input: string | string[], char: string, toUpper: boolean): string

Convert a string to text where words are separated by a given character (e.g. this#is#character#separated)

#Parameter NameRequiredTypeDefault
0inputYesstring | string[]
1charNostring','
2toUpperNobooleanfalse
Return Type
string

[↑ Back to StringTools ↑]

toSlugCase
StringTools.toSlugCase(input: string | string[], toUpper: boolean): string
StringTools.fromSlugCase.toSlugCase(input: string | string[], toUpper: boolean): string
StringTools.fromSnakeCase.toSlugCase(input: string | string[], toUpper: boolean): string
StringTools.fromSpaced.toSlugCase(input: string | string[], toUpper: boolean): string
StringTools.fromCamelCase.toSlugCase(input: string | string[], toUpper: boolean): string

Convert a string to camel case (e.g. this-is-slug-case)

#Parameter NameRequiredTypeDefault
0inputYesstring | string[]
1toUpperNobooleanfalse
Return Type
string

[↑ Back to StringTools ↑]

toLowerSlugCase
StringTools.toLowerSlugCase(input: string | string[]): string
StringTools.fromSlugCase.toLowerSlugCase(input: string | string[]): string
StringTools.fromSnakeCase.toLowerSlugCase(input: string | string[]): string
StringTools.fromSpaced.toLowerSlugCase(input: string | string[]): string
StringTools.fromCamelCase.toLowerSlugCase(input: string | string[]): string

Convert a string to lower slug case (e.g. this-is-lower-slug-case)

#Parameter NameRequiredType
0inputYesstring | string[]
Return Type
string

[↑ Back to StringTools ↑]

toUpperSlugCase
StringTools.toUpperSlugCase(input: string | string[]): string
StringTools.fromSlugCase.toUpperSlugCase(input: string | string[]): string
StringTools.fromSnakeCase.toUpperSlugCase(input: string | string[]): string
StringTools.fromSpaced.toUpperSlugCase(input: string | string[]): string
StringTools.fromCamelCase.toUpperSlugCase(input: string | string[]): string

Convert a string to upper camel case (e.g. THIS-IS-UPPER-SLUG-CASE)

#Parameter NameRequiredType
0inputYesstring | string[]
Return Type
string

[↑ Back to StringTools ↑]

toSnakeCase
StringTools.toSnakeCase(input: string | string[], toUpper: boolean): string
StringTools.fromSlugCase.toSnakeCase(input: string | string[], toUpper: boolean): string
StringTools.fromSnakeCase.toSnakeCase(input: string | string[], toUpper: boolean): string
StringTools.fromSpaced.toSnakeCase(input: string | string[], toUpper: boolean): string
StringTools.fromCamelCase.toSnakeCase(input: string | string[], toUpper: boolean): string

Convert a string to snake case (e.g. this_is_snake_case)

#Parameter NameRequiredTypeDefault
0inputYesstring | string[]
1toUpperNobooleanfalse
Return Type
string

[↑ Back to StringTools ↑]

toLowerSnakeCase
StringTools.toLowerSnakeCase(input: string | string[]): string
StringTools.fromSlugCase.toLowerSnakeCase(input: string | string[]): string
StringTools.fromSnakeCase.toLowerSnakeCase(input: string | string[]): string
StringTools.fromSpaced.toLowerSnakeCase(input: string | string[]): string
StringTools.fromCamelCase.toLowerSnakeCase(input: string | string[]): string

Convert a string to lower snake case (e.g. this_is_lower_snake_case)

#Parameter NameRequiredType
0inputYesstring | string[]
Return Type
string

[↑ Back to StringTools ↑]

toUpperSnakeCase
StringTools.toUpperSnakeCase(input: string | string[]): string
StringTools.fromSlugCase.toUpperSnakeCase(input: string | string[]): string
StringTools.fromSnakeCase.toUpperSnakeCase(input: string | string[]): string
StringTools.fromSpaced.toUpperSnakeCase(input: string | string[]): string
StringTools.fromCamelCase.toUpperSnakeCase(input: string | string[]): string

Convert a string to upper snake case (e.g. THIS_IS_UPPER_SNAKE_CASE)

#Parameter NameRequiredType
0inputYesstring | string[]
Return Type
string

[↑ Back to StringTools ↑]

toSpaced
StringTools.toSpaced(input: string | string[], toUpper: boolean): string
StringTools.fromSlugCase.toSpaced(input: string | string[], toUpper: boolean): string
StringTools.fromSnakeCase.toSpaced(input: string | string[], toUpper: boolean): string
StringTools.fromSpaced.toSpaced(input: string | string[], toUpper: boolean): string
StringTools.fromCamelCase.toSpaced(input: string | string[], toUpper: boolean): string

Convert a string to spaced case (e.g. this is spaced case)

#Parameter NameRequiredTypeDefault
0inputYesstring | string[]
1toUpperNobooleanfalse
Return Type
string

[↑ Back to StringTools ↑]

toLowerSpaced
StringTools.toLowerSpaced(input: string | string[]): string
StringTools.fromSlugCase.toLowerSpaced(input: string | string[]): string
StringTools.fromSnakeCase.toLowerSpaced(input: string | string[]): string
StringTools.fromSpaced.toLowerSpaced(input: string | string[]): string
StringTools.fromCamelCase.toLowerSpaced(input: string | string[]): string

Convert a string to lower spaced case (e.g. this is lower spaced case)

#Parameter NameRequiredType
0inputYesstring | string[]
Return Type
string

[↑ Back to StringTools ↑]

toUpperSpaced
StringTools.toUpperSpaced(input: string | string[]): string
StringTools.fromSlugCase.toUpperSpaced(input: string | string[]): string
StringTools.fromSnakeCase.toUpperSpaced(input: string | string[]): string
StringTools.fromSpaced.toUpperSpaced(input: string | string[]): string
StringTools.fromCamelCase.toUpperSpaced(input: string | string[]): string

Convert a string to upper spaced case (e.g. THIS IS UPPER SPACED CASE)

#Parameter NameRequiredType
0inputYesstring | string[]
Return Type
string

[↑ Back to StringTools ↑]

toCapitalisedSpaced
StringTools.toCapitalisedSpaced(input: string | string[]): string
StringTools.fromSlugCase.toCapitalisedSpaced(input: string | string[]): string
StringTools.fromSnakeCase.toCapitalisedSpaced(input: string | string[]): string
StringTools.fromSpaced.toCapitalisedSpaced(input: string | string[]): string
StringTools.fromCamelCase.toCapitalisedSpaced(input: string | string[]): string

Convert a string to capitalised spaced case (e.g. This Is Capitalised Spaced Case)

#Parameter NameRequiredType
0inputYesstring | string[]
Return Type
string

[↑ Back to StringTools ↑]

fromSlugCase
StringTools.fromSlugCase.toLowerCamelCase;
StringTools.fromSlugCase.toUpperCamelCase;
StringTools.fromSlugCase.toCamelCase;
StringTools.fromSlugCase.toLowerSlugCase;
StringTools.fromSlugCase.toUpperSlugCase;
StringTools.fromSlugCase.toSlugCase;
StringTools.fromSlugCase.toLowerSnakeCase;
StringTools.fromSlugCase.toUpperSnakeCase;
StringTools.fromSlugCase.toSnakeCase;
StringTools.fromSlugCase.toLowerSpaced;
StringTools.fromSlugCase.toUpperSpaced;
StringTools.fromSlugCase.toCapitalisedSpaced;
StringTools.fromSlugCase.toSpaced;
StringTools.fromSlugCase.toCharacterSeparated;

Has the following methods:

[↑ Back to StringTools ↑]

fromSnakeCase
StringTools.fromSnakeCase.toLowerCamelCase;
StringTools.fromSnakeCase.toUpperCamelCase;
StringTools.fromSnakeCase.toCamelCase;
StringTools.fromSnakeCase.toLowerSlugCase;
StringTools.fromSnakeCase.toUpperSlugCase;
StringTools.fromSnakeCase.toSlugCase;
StringTools.fromSnakeCase.toLowerSnakeCase;
StringTools.fromSnakeCase.toUpperSnakeCase;
StringTools.fromSnakeCase.toSnakeCase;
StringTools.fromSnakeCase.toLowerSpaced;
StringTools.fromSnakeCase.toUpperSpaced;
StringTools.fromSnakeCase.toCapitalisedSpaced;
StringTools.fromSnakeCase.toSpaced;
StringTools.fromSnakeCase.toCharacterSeparated;

Has the following methods:

[↑ Back to StringTools ↑]

fromSpaced
StringTools.fromSpaced.toLowerCamelCase;
StringTools.fromSpaced.toUpperCamelCase;
StringTools.fromSpaced.toCamelCase;
StringTools.fromSpaced.toLowerSlugCase;
StringTools.fromSpaced.toUpperSlugCase;
StringTools.fromSpaced.toSlugCase;
StringTools.fromSpaced.toLowerSnakeCase;
StringTools.fromSpaced.toUpperSnakeCase;
StringTools.fromSpaced.toSnakeCase;
StringTools.fromSpaced.toLowerSpaced;
StringTools.fromSpaced.toUpperSpaced;
StringTools.fromSpaced.toCapitalisedSpaced;
StringTools.fromSpaced.toSpaced;
StringTools.fromSpaced.toCharacterSeparated;

Has the following methods:

[↑ Back to StringTools ↑]

fromCamelCase
StringTools.fromCamelCase.toLowerCamelCase;
StringTools.fromCamelCase.toUpperCamelCase;
StringTools.fromCamelCase.toCamelCase;
StringTools.fromCamelCase.toLowerSlugCase;
StringTools.fromCamelCase.toUpperSlugCase;
StringTools.fromCamelCase.toSlugCase;
StringTools.fromCamelCase.toLowerSnakeCase;
StringTools.fromCamelCase.toUpperSnakeCase;
StringTools.fromCamelCase.toSnakeCase;
StringTools.fromCamelCase.toLowerSpaced;
StringTools.fromCamelCase.toUpperSpaced;
StringTools.fromCamelCase.toCapitalisedSpaced;
StringTools.fromCamelCase.toSpaced;
StringTools.fromCamelCase.toCharacterSeparated;

Has the following methods:

[↑ Back to StringTools ↑]

matchBrackets

Tools for matching corresponding brackets in a string

[↑ Back to StringTools ↑]

unique
StringTools.matchBrackets.unique(input: string, replaceSymbols: Partial<BracketReplaceSymbols>): string

Replace brackets with symbols and with a unique ID for each bracket pair of each type

const example = '{name: "Jane", info: { age: 31, interests: ["Tennis", "Board Games"] }}';
const uniqued = matchBrackets.unique(example);
uniqued; // '❴0✧name: "Jane", info: ❴1✧ age: 31, interests: ❲0✧"Tennis", "Board Games"❳0✧ ❵1✧❵0✧'
#Parameter NameRequiredTypeDefault
0inputYesstring
1replaceSymbolsNoPartial<BracketReplaceSymbols>{}
Return Type
string

[↑ Back to StringTools ↑]

depth
StringTools.matchBrackets.depth(input: string, replaceSymbols: Partial<BracketReplaceSymbols>): string

Replace brackets with symbols and with a numbers for how deep each bracket pair is for that bracket type

const example = '{name: "Jane", info: { age: 31, interests: ["Tennis", "Board Games"] }}';
const depthed = matchBrackets.depth(example);
depthed; // '❴0✧name: "Jane", info: ❴1✧ age: 31, interests: ❲0✧"Tennis", "Board Games"❳0✧ ❵1✧❵0✧'
#Parameter NameRequiredTypeDefault
0inputYesstring
1replaceSymbolsNoPartial<BracketReplaceSymbols>{}
Return Type
string

[↑ Back to StringTools ↑]

clean
StringTools.matchBrackets.clean(input: string, replaceSymbols: Partial<BracketReplaceSymbols>): string

Return a string that's been matched with unique or depth and replace the symbols with the original brackets. Also works with substrings of such strings.

const example = '{name: "Jane", info: { age: 31, interests: ["Tennis", "Board Games"] }}';
const uniqued = matchBrackets.unique(example);
uniqued; // '❴0✧name: "Jane", info: ❴1✧ age: 31, interests: ❲0✧"Tennis", "Board Games"❳0✧ ❵1✧❵0✧'

const cleaned = matchBrackets.clean(uniqued);
cleaned; // '{name: "Jane", info: { age: 31, interests: ["Tennis", "Board Games"] }}'
#Parameter NameRequiredTypeDefault
0inputYesstring
1replaceSymbolsNoPartial<BracketReplaceSymbols>{}
Return Type
string

[↑ Back to StringTools ↑]

grabDepth
StringTools.matchBrackets.grabDepth(input: string, bracketType: '()' | '[]' | '{}' | '<>' | 'round' | 'square' | 'curly' | 'angle', depthID: number, replaceSymbols: Partial<BracketReplaceSymbols>): string[]

Obtain all the bracketed substrings of the given bracket type from a string at a given depth.

const example = `[
  [
    [1, 2, 3],
    [4, 5, 6]
  ],
  [
    [7, 8, 9]
  ]
]`;
const grabbed = matchBrackets.grabDepth(example, 'square', 2);
grabbed; // [ '[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]' ]
#Parameter NameRequiredTypeDefault
0inputYesstring
1bracketTypeNo'()' | '[]' | '{}' | '<>' | 'round' | 'square' | 'curly' | 'angle''round'
2depthIDNonumber0
3replaceSymbolsNoPartial<BracketReplaceSymbols>{}
Return Type
string[]

[↑ Back to StringTools ↑]

grabUnique
StringTools.matchBrackets.grabUnique(input: string, bracketType: '()' | '[]' | '{}' | '<>' | 'round' | 'square' | 'curly' | 'angle', uniqueID: number, replaceSymbols: Partial<BracketReplaceSymbols>): string

Obtain all the bracketed substring of the given bracket type from a string with the given unique ID. e.g. if uniqueID is 3, it will return the bracketed substring for the 4th instance of the opening bracket (see StringTools.matchBrackets.unique)

const example = `[
  [
    [1, 2, 3],
    [4, 5, 6]
  ],
  [
    [7, 8, 9]
  ]
]`;
const grabbed = matchBrackets.grabUnique(example, 'square', 3);
grabbed; // '[4, 5, 6]'
#Parameter NameRequiredTypeDefault
0inputYesstring
1bracketTypeNo'()' | '[]' | '{}' | '<>' | 'round' | 'square' | 'curly' | 'angle''round'
2uniqueIDNonumber0
3replaceSymbolsNoPartial<BracketReplaceSymbols>{}
Return Type
string

[↑ Back to StringTools ↑]

grab
StringTools.matchBrackets.grab(input: string, bracketType: '()' | '[]' | '{}' | '<>' | 'round' | 'square' | 'curly' | 'angle', replaceSymbols: Partial<BracketReplaceSymbols>): string[]

Grab all the bracketed substrings from a string of the given bracket type.

const example = `[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9]]]`;
matchBrackets.grab(example, 'square');
// [
//   '[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9]]]',
//   '[[1, 2, 3], [4, 5, 6]]',
//   '[1, 2, 3]',
//   '[4, 5, 6]',
//   '[[7, 8, 9]]',
//   '[7, 8, 9]'
// ]
#Parameter NameRequiredTypeDefault
0inputYesstring
1bracketTypeNo'()' | '[]' | '{}' | '<>' | 'round' | 'square' | 'curly' | 'angle''round'
2replaceSymbolsNoPartial<BracketReplaceSymbols>{}
Return Type
string[]

[↑ Back to StringTools ↑]

getReplaceSymbols
StringTools.matchBrackets.getReplaceSymbols(replaceSymbols: Partial<BracketReplaceSymbols>): BracketReplaceSymbols

Get a full set of replace symbols

matchBrackets.getReplaceSymbols();
// {
//   END: '✧',
//   '(': '❪',
//   ')': '❫',
//   '[': '❲',
//   ']': '❳',
//   '{': '❴',
//   '}': '❵',
//   '<': '❰',
//   '>': '❱'
// }

matchBrackets.getReplaceSymbols({
  END: '▣',
  '{': 'START_CURLY',
  '}': 'END_CURLY'
})
// {
//   END: '▣',
//   '(': '❪',
//   ')': '❫',
//   '[': '❲',
//   ']': '❳',
//   '{': 'START_CURLY',
//   '}': 'END_CURLY',
//   '<': '❰',
//   '>': '❱'
// }
#Parameter NameRequiredTypeDefault
0replaceSymbolsNoPartial<BracketReplaceSymbols>{}
Return Type
BracketReplaceSymbols

[↑ Back to StringTools ↑]

BracketReplaceSymbols
StringTools.matchBrackets.BracketReplaceSymbols;

Type for controlling the symbols used to replace brackets

{
  END: string;
  '(': string;
  ')': string;
  '[': string;
  ']': string;
  '{': string;
  '}': string;
  '<': string;
  '>': string;
}

[↑ Back to StringTools ↑]

MathsTools

A collection of mathematical functions.

Note: The field is 'Mathematics', and so it is 'MathsTools' not 'MathTools'

[↑ Back to top ↑]

fixFloat

ff(num: number): number
MathsTools.ff(num: number): number
MathsTools.fixFloat(num: number): number

Fixes floating point errors that may occur when adding/subtracting/multiplying/dividing real/float numbers

Can also be used to round numbers to a given precision

Note: 'fixFloat' is not a great name, but it's what I've always called it, so I'm sticking with it. 'ff' is a shorthand alias.

0.1 + 0.2 // 0.30000000000000004
MathsTools.fixFloat(0.1 + 0.2) // 0.3
#Parameter NameRequiredType
0numYesnumber
Return Type
number

[↑ Back to MathsTools ↑]

addAll

MathsTools.addAll(...nums: number[]): number

Adds all numbers together. Each argument is a number (use spread operator to pass in an array) similar to Math.min/Math.max

MathsTools.addAll(1, 2, 3, 4, 5); // 15
#Parameter NameRequiredType
0…numsNonumber[]
Return Type
number

[↑ Back to MathsTools ↑]

round

floorTo
MathsTools.floorTo(to: number, value: number): number
MathsTools.round.floorTo(to: number, value: number): number

Floors a number down to the nearest multiple of the given number.

MathsTools.round.floorTo(10, 102); // 100
MathsTools.round.floorTo(5, 53); // 50
MathsTools.round.floorTo(0.1, 0.25); // 0.2
#Parameter NameRequiredType
0toYesnumber
1valueYesnumber
Return Type
number

[↑ Back to MathsTools ↑]

roundTo
MathsTools.round.to(to: number, value: number): number
MathsTools.roundTo(to: number, value: number): number
MathsTools.round.roundTo(to: number, value: number): number

Floors a number down to the nearest multiple of the given number.

MathsTools.round.to(10, 102); // 100
MathsTools.round.to(5, 53); // 55
MathsTools.round.to(0.1, 0.25); // 0.3
#Parameter NameRequiredType
0toYesnumber
1valueYesnumber
Return Type
number

[↑ Back to MathsTools ↑]

ceilTo
MathsTools.ceilTo(to: number, value: number): number
MathsTools.round.ceilTo(to: number, value: number): number

Floors a number down to the nearest multiple of the given number.

MathsTools.round.ceilTo(10, 102); // 110
MathsTools.round.ceilTo(5, 53); // 55
MathsTools.round.ceilTo(0.1, 0.25); // 0.3
#Parameter NameRequiredType
0toYesnumber
1valueYesnumber
Return Type
number

[↑ Back to MathsTools ↑]

lerp

MathsTools.lerp(progress: number, fromVal: number, toVal: number): number

Linearly interpolates between two values.

MathsTools.lerp(0.5, 0, 10); // 5
#Parameter NameRequiredType
0progressYesnumber
1fromValYesnumber
2toValYesnumber
Return Type
number

[↑ Back to MathsTools ↑]

lerpArray

MathsTools.lerpArray(progress: number, fromArr: number[], toArr: number[]): number[]

Linearly interpolates between the values of 2 arrays.

MathsTools.lerpArray(0.5, [0, 0, 0], [10, 100, 1000]) // [5, 50, 500]
#Parameter NameRequiredType
0progressYesnumber
1fromArrYesnumber[]
2toArrYesnumber[]
Return Type
number[]

[↑ Back to MathsTools ↑]

lerpObj

MathsTools.lerpObj(progress: number, fromObj: T, toObj: T): T

Linearly interpolates between the values of 2 arrays.

MathsTools.lerpObj(0.5, {'ARS': 0, 'CHE': 0, 'FUL': 0}, {'ARS': 100, 'CHE': 10, 'FUL': 20}) // {'ARS': 50, 'CHE': 5, 'FUL': 10}
#Parameter NameRequiredType
0progressYesnumber
1fromObjYesT
2toObjYesT
Return Type
T

[↑ Back to MathsTools ↑]

clamp

MathsTools.clamp(value: number, min: number, max: number): number

Clamps a value between a min and max.

MathsTools.clamp(5, 0, 10); // 5
MathsTools.clamp(-5, 0, 10); // 0
#Parameter NameRequiredType
0valueYesnumber
1minYesnumber
2maxYesnumber
Return Type
number

[↑ Back to MathsTools ↑]

getOrdinal

MathsTools.getOrdinal(num: number): "th" | "st" | "nd" | "rd"

Gets the ordinal suffix for a number.

Note: all numbers are treated as positive. Note: all decimals are 'th' (e.g. 1.2 is '1.2th') as they are tenth, hundredth, thousandth, etc.

MathsTools.getOrdinal(1); // 'st'
MathsTools.getOrdinal(2); // 'nd'
MathsTools.getOrdinal(3); // 'rd'
MathsTools.getOrdinal(4); // 'th'

MathsTools.getOrdinal(11); // 'th'
MathsTools.getOrdinal(12); // 'th'
MathsTools.getOrdinal(13); // 'th'
MathsTools.getOrdinal(14); // 'th'

MathsTools.getOrdinal(21); // 'st'
MathsTools.getOrdinal(22); // 'nd'
MathsTools.getOrdinal(23); // 'rd'
MathsTools.getOrdinal(24); // 'th'
#Parameter NameRequiredTypeDefault
0numNonumber0
Return Type
"th" | "st" | "nd" | "rd"

[↑ Back to MathsTools ↑]

PromiseTools

A collection of promise utilities

[↑ Back to top ↑]

getDeferred

getDeferred(): DeferredPromise<T>
PromiseTools.getDeferred(): DeferredPromise<T>

A deferred promise

import { getDeferred } from 'swiss-ak';

const run = () => {
  const deferred = getDeferred<number>();

  doSomethingWithACallback('a', 'b', (err: Error, result: number) => {
    // callback (just an example - don't actually do this this way)
    if (err) return deferred.reject(err);
    deferred.resolve(result);
  });

  return deferred.promise;
};

const luckyNumber: number = await run();
Return Type
DeferredPromise<T>

[↑ Back to PromiseTools ↑]

all

all(items: PromiseTools.PromiseItem<T>[]): Promise<T[]>
PromiseTools.all(items: PromiseTools.PromiseItem<T>[]): Promise<T[]>

Similar to Promise.all, but accepts values, functions, and promises.

#Parameter NameRequiredType
0itemsYesPromiseTools.PromiseItem<T>[]
Return Type
Promise<T[]>

[↑ Back to PromiseTools ↑]

allLimit

allLimit(limit: number, items: PromiseTools.PromiseItem<T>[], noThrow: boolean): Promise<T[]>
PromiseTools.allLimit(limit: number, items: PromiseTools.PromiseItem<T>[], noThrow: boolean): Promise<T[]>

Like Promise.all, but limits the numbers of concurrently running items.

Takes an array of functions (that return Promises), rather than an array of Promises

import { PromiseTools, timer, ms, seconds } from 'swiss-ak';

const give = async (delay: ms, result: number, label: string) => {
  await waitFor(delay);
  timer.end(label);
  return result;
};

timer.start('allLimit', 'a', 'b', 'c', 'd');

const results = PromiseTools.allLimit<number>(2, [
  give(seconds(5), 1, 'a'),
  give(seconds(5), 2, 'b'),
  give(seconds(5), 3, 'c'),
  give(seconds(5), 4, 'd')
]);

timer.end('allLimit');

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

timer.log();
// Times:
// 	allLimit: 10s
// 	a: 5s
// 	b: 5s
// 	c: 10s
// 	d: 10s
#Parameter NameRequiredTypeDefault
0limitYesnumber
1itemsYesPromiseTools.PromiseItem<T>[]
2noThrowNobooleanfalse
Return Type
Promise<T[]>

[↑ Back to PromiseTools ↑]

each

each(items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<any>): Promise<void>
PromiseTools.each(items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<any>): Promise<void>

Run an async function against each item in an array

import { PromiseTools, ms, seconds, wait } from 'swiss-ak';

const arr = [1, 2, 3, 4];

await PromiseTools.each<number>(arr, async (val: number) => {
  await wait(seconds(2));
  sendToSomewhere(val);
});
console.log(''); // after 2 seconds
#Parameter NameRequiredType
0itemsYesTi[]
1funcYes(item: Ti, index: number, array: Ti[]) => Promise<any>
Return Type
Promise<void>

[↑ Back to PromiseTools ↑]

eachLimit

eachLimit(limit: number, items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<any>): Promise<void>
PromiseTools.eachLimit(limit: number, items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<any>): Promise<void>

Run an async function against each item in an array, limiting the number of items that can run concurrently.

See PromiseTools.allLimit for information about limited functions.

import { PromiseTools, ms, seconds, wait } from 'swiss-ak';

const arr = [1, 2, 3, 4];

await PromiseTools.eachLimit<number>(2, arr, async (val: number) => {
  await wait(seconds(2));
  sendToSomewhere(val);
});
console.log(''); // after 4 seconds
#Parameter NameRequiredType
0limitYesnumber
1itemsYesTi[]
2funcYes(item: Ti, index: number, array: Ti[]) => Promise<any>
Return Type
Promise<void>

[↑ Back to PromiseTools ↑]

map

map(items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<To>): Promise<To[]>
PromiseTools.map(items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<To>): Promise<To[]>

Run an async map function against each item in an array, mapping the results to a returned array

import { PromiseTools, ms, seconds, wait } from 'swiss-ak';

const arr = [1, 2, 3, 4];

const mapped = await PromiseTools.map<number>(arr, async (val: number) => {
  await wait(seconds(2));
  return val * 2;
});

console.log(mapped); // [2, 4, 6, 8] (after 2 seconds)
#Parameter NameRequiredType
0itemsYesTi[]
1funcYes(item: Ti, index: number, array: Ti[]) => Promise<To>
Return Type
Promise<To[]>

[↑ Back to PromiseTools ↑]

mapLimit

mapLimit(limit: number, items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<To>): Promise<To[]>
PromiseTools.mapLimit(limit: number, items: Ti[], func: (item: Ti, index: number, array: Ti[]) => Promise<To>): Promise<To[]>

Run an async map function against each item in an array, mapping the results to a returned array, and limiting the number of items that can run concurrently.

See PromiseTools.allLimit for information about limited functions.

import { PromiseTools, ms, seconds, wait } from 'swiss-ak';

const arr = [1, 2, 3, 4];

const mapped = await PromiseTools.mapLimit<number>(2, arr, async (val: number) => {
  await wait(seconds(2));
  return val * 2;
});

console.log(mapped); // [2, 4, 6, 8] (after 4 seconds)
#Parameter NameRequiredType
0limitYesnumber
1itemsYesTi[]
2funcYes(item: Ti, index: number, array: Ti[]) => Promise<To>
Return Type
Promise<To[]>

[↑ Back to PromiseTools ↑]

allObj

allObj(input: T): Promise<UnWrapPromiseObject<T>>
PromiseTools.allObj(input: T): Promise<UnWrapPromiseObject<T>>

Like Promise.all, but pass/receive objects rather than arrays

import { PromiseTools, timer, ms, seconds } from 'swiss-ak';

const give = async (delay: ms, result: number, label: string) => {
  await waitFor(delay);
  timer.end(label);
  return result;
};

timer.start('allObj', 'a', 'b', 'c');

const results = PromiseTools.allObj<number>({
  a: give(seconds(10), 1, 'a'),
  b: give(seconds(15), 2, 'b'),
  c: give(seconds(20), 3, 'c')
});

timer.end('allObj');

console.log(results); // { a: 1, b: 2, c: 3 }

timer.log();
// Times:
// 	allObj: 20s
// 	a: 10s
// 	b: 15s
// 	c: 20s
#Parameter NameRequiredType
0inputYesT
Return Type
Promise<UnWrapPromiseObject<T>>

[↑ Back to PromiseTools ↑]

allLimitObj

allLimitObj(limit: number, input: T, noThrow: boolean): Promise<UnWrapPromiseObject<T>>
PromiseTools.allLimitObj(limit: number, input: T, noThrow: boolean): Promise<UnWrapPromiseObject<T>>

A mix of allObj and allLimit.

Takes an array of functions (that return Promises), and limits the numbers of concurrently running items.

import { PromiseTools, timer, ms, seconds } from 'swiss-ak';

const give = async (delay: ms, result: number, label: string) => {
  await waitFor(delay);
  timer.end(label);
  return result;
};

timer.start('allLimitObj', 'a', 'b', 'c', 'd');

const results = PromiseTools.allLimitObj<number>(2, {
  a: give(seconds(5), 1, 'a'),
  b: give(seconds(5), 2, 'b'),
  c: give(seconds(5), 3, 'c'),
  d: give(seconds(5), 4, 'd')
});

timer.end('allLimitObj');

console.log(results); // { a: 1, b: 2, c: 3, d: 4 }

timer.log();
// Times:
// 	allLimitObj: 10s
// 	a: 5s
// 	b: 5s
// 	c: 10s
// 	d: 10s
#Parameter NameRequiredTypeDefault
0limitYesnumber
1inputYesT
2noThrowNobooleanfalse
Return Type
Promise<UnWrapPromiseObject<T>>

[↑ Back to PromiseTools ↑]

PromiseFunc

PromiseFunc<T>;

A function that returns a promise

[↑ Back to PromiseTools ↑]

PromiseItem

PromiseItem<T>;

A promise, a function that returns a promise (see PromiseFunc), or a value

Accepted by PromiseTools.all, PromiseTools.allLimit, PromiseTools.allObj, and PromiseTools.allLimitObj in place of promises

[↑ Back to PromiseTools ↑]

DeferredPromise

DeferredPromise;
PromiseTools.DeferredPromise;

A deferred promise

[↑ Back to PromiseTools ↑]

ColourTools

A collection of functions for working with colours.

[↑ Back to top ↑]

ColourValues

ColourTools.ColourValues;

A type with 3 numbers:

  • red [0-255]
  • green [0-255]
  • blue [0-255]

[↑ Back to ColourTools ↑]

HSLValues

ColourTools.HSLValues;

A type with 3 numbers:

  • hue [0-360]
  • saturation [0-100]
  • lightness [0-100]

[↑ Back to ColourTools ↑]

namedColours

ColourTools.namedColours;

A dictionary of different colour names and their RGB values

NameRGBHex
aliceblue240, 248, 255#f0f8ff
antiquewhite250, 235, 215#faebd7
aqua0, 255, 255#00ffff
aquamarine127, 255, 212#7fffd4
azure240, 255, 255#f0ffff
beige245, 245, 220#f5f5dc
bisque255, 228, 196#ffe4c4
black0, 0, 0#000000
blanchedalmond255, 235, 205#ffebcd
blue0, 0, 255#0000ff
blueviolet138, 43, 226#8a2be2
brown165, 42, 42#a52a2a
burlywood222, 184, 135#deb887
cadetblue95, 158, 160#5f9ea0
chartreuse127, 255, 0#7fff00
chocolate210, 105, 30#d2691e
coral255, 127, 80#ff7f50
cornflowerblue100, 149, 237#6495ed
cornsilk255, 248, 220#fff8dc
crimson220, 20, 60#dc143c
cyan0, 255, 255#00ffff
darkblue0, 0, 139#00008b
darkcyan0, 139, 139#008b8b
darkgoldenrod184, 134, 11#b8860b
darkgray169, 169, 169#a9a9a9
darkgreen0, 100, 0#006400
darkgrey169, 169, 169#a9a9a9
darkkhaki189, 183, 107#bdb76b
darkmagenta139, 0, 139#8b008b
darkolivegreen85, 107, 47#556b2f
darkorange255, 140, 0#ff8c00
darkorchid153, 50, 204#9932cc
darkred139, 0, 0#8b0000
darksalmon233, 150, 122#e9967a
darkseagreen143, 188, 143#8fbc8f
darkslateblue72, 61, 139#483d8b
darkslategray47, 79, 79#2f4f4f
darkslategrey47, 79, 79#2f4f4f
darkturquoise0, 206, 209#00ced1
darkviolet148, 0, 211#9400d3
deeppink255, 20, 147#ff1493
deepskyblue0, 191, 255#00bfff
dimgray105, 105, 105#696969
dimgrey105, 105, 105#696969
dodgerblue30, 144, 255#1e90ff
firebrick178, 34, 34#b22222
floralwhite255, 250, 240#fffaf0
forestgreen34, 139, 34#228b22
fractal128, 128, 128#808080
fuchsia255, 0, 255#ff00ff
gainsboro220, 220, 220#dcdcdc
ghostwhite248, 248, 255#f8f8ff
gold255, 215, 0#ffd700
goldenrod218, 165, 32#daa520
gray00, 0, 0#000000
gray13, 3, 3#030303
gray25, 5, 5#050505
gray38, 8, 8#080808
gray410, 10, 10#0a0a0a
gray513, 13, 13#0d0d0d
gray615, 15, 15#0f0f0f
gray718, 18, 18#121212
gray820, 20, 20#141414
gray923, 23, 23#171717
gray1026, 26, 26#1a1a1a
gray1128, 28, 28#1c1c1c
gray1231, 31, 31#1f1f1f
gray1333, 33, 33#212121
gray1436, 36, 36#242424
gray1538, 38, 38#262626
gray1641, 41, 41#292929
gray1743, 43, 43#2b2b2b
gray1846, 46, 46#2e2e2e
gray1948, 48, 48#303030
gray2051, 51, 51#333333
gray2154, 54, 54#363636
gray2256, 56, 56#383838
gray2359, 59, 59#3b3b3b
gray2461, 61, 61#3d3d3d
gray2564, 64, 64#404040
gray2666, 66, 66#424242
gray2769, 69, 69#454545
gray2871, 71, 71#474747
gray2974, 74, 74#4a4a4a
gray3077, 77, 77#4d4d4d
gray3179, 79, 79#4f4f4f
gray3282, 82, 82#525252
gray3384, 84, 84#545454
gray3487, 87, 87#575757
gray3589, 89, 89#595959
gray3692, 92, 92#5c5c5c
gray3794, 94, 94#5e5e5e
gray3897, 97, 97#616161
gray3999, 99, 99#636363
gray40102, 102, 102#666666
gray41105, 105, 105#696969
gray42107, 107, 107#6b6b6b
gray43110, 110, 110#6e6e6e
gray44112, 112, 112#707070
gray45115, 115, 115#737373
gray46117, 117, 117#757575
gray47120, 120, 120#787878
gray48122, 122, 122#7a7a7a
gray49125, 125, 125#7d7d7d
gray50127, 127, 127#7f7f7f
gray51130, 130, 130#828282
gray52133, 133, 133#858585
gray53135, 135, 135#878787
gray54138, 138, 138#8a8a8a
gray55140, 140, 140#8c8c8c
gray56143, 143, 143#8f8f8f
gray57145, 145, 145#919191
gray58148, 148, 148#949494
gray59150, 150, 150#969696
gray60153, 153, 153#999999
gray61156, 156, 156#9c9c9c
gray62158, 158, 158#9e9e9e
gray63161, 161, 161#a1a1a1
gray64163, 163, 163#a3a3a3
gray65166, 166, 166#a6a6a6
gray66168, 168, 168#a8a8a8
gray67171, 171, 171#ababab
gray68173, 173, 173#adadad
gray69176, 176, 176#b0b0b0
gray70179, 179, 179#b3b3b3
gray71181, 181, 181#b5b5b5
gray72184, 184, 184#b8b8b8
gray73186, 186, 186#bababa
gray74189, 189, 189#bdbdbd
gray75191, 191, 191#bfbfbf
gray76194, 194, 194#c2c2c2
gray77196, 196, 196#c4c4c4
gray78199, 199, 199#c7c7c7
gray79201, 201, 201#c9c9c9
gray80204, 204, 204#cccccc
gray81207, 207, 207#cfcfcf
gray82209, 209, 209#d1d1d1
gray83212, 212, 212#d4d4d4
gray84214, 214, 214#d6d6d6
gray85217, 217, 217#d9d9d9
gray86219, 219, 219#dbdbdb
gray87222, 222, 222#dedede
gray88224, 224, 224#e0e0e0
gray89227, 227, 227#e3e3e3
gray90229, 229, 229#e5e5e5
gray91232, 232, 232#e8e8e8
gray92235, 235, 235#ebebeb
gray93237, 237, 237#ededed
gray94240, 240, 240#f0f0f0
gray95242, 242, 242#f2f2f2
gray96245, 245, 245#f5f5f5
gray97247, 247, 247#f7f7f7
gray98250, 250, 250#fafafa
gray99252, 252, 252#fcfcfc
gray100255, 255, 255#ffffff
gray126, 126, 126#7e7e7e
green0, 128, 0#008000
greenyellow173, 255, 47#adff2f
grey128, 128, 128#808080
honeydew240, 255, 240#f0fff0
hotpink255, 105, 180#ff69b4
indianred205, 92, 92#cd5c5c
indigo75, 0, 130#4b0082
ivory255, 255, 240#fffff0
khaki240, 230, 140#f0e68c
lavender230, 230, 250#e6e6fa
lavenderblush255, 240, 245#fff0f5
lawngreen124, 252, 0#7cfc00
lemonchiffon255, 250, 205#fffacd
lightblue173, 216, 230#add8e6
lightcoral240, 128, 128#f08080
lightcyan224, 255, 255#e0ffff
lightgoldenrodyellow250, 250, 210#fafad2
lightgray211, 211, 211#d3d3d3
lightgreen144, 238, 144#90ee90
lightgrey211, 211, 211#d3d3d3
lightpink255, 182, 193#ffb6c1
lightsalmon255, 160, 122#ffa07a
lightseagreen32, 178, 170#20b2aa
lightskyblue135, 206, 250#87cefa
lightslategray119, 136, 153#778899
lightslategrey119, 136, 153#778899
lightsteelblue176, 196, 222#b0c4de
lightyellow255, 255, 224#ffffe0
lime0, 255, 0#00ff00
limegreen50, 205, 50#32cd32
linen250, 240, 230#faf0e6
magenta255, 0, 255#ff00ff
maroon128, 0, 0#800000
mediumaquamarine102, 205, 170#66cdaa
mediumblue0, 0, 205#0000cd
mediumorchid186, 85, 211#ba55d3
mediumpurple147, 112, 219#9370db
mediumseagreen60, 179, 113#3cb371
mediumslateblue123, 104, 238#7b68ee
mediumspringgreen0, 250, 154#00fa9a
mediumturquoise72, 209, 204#48d1cc
mediumvioletred199, 21, 133#c71585
midnightblue25, 25, 112#191970
mintcream245, 255, 250#f5fffa
mistyrose255, 228, 225#ffe4e1
moccasin255, 228, 181#ffe4b5
navajowhite255, 222, 173#ffdead
navy0, 0, 128#000080
none0, 0, 0#000000
oldlace253, 245, 230#fdf5e6
olive128, 128, 0#808000
olivedrab107, 142, 35#6b8e23
orange255, 165, 0#ffa500
orangered255, 69, 0#ff4500
orchid218, 112, 214#da70d6
palegoldenrod238, 232, 170#eee8aa
palegreen152, 251, 152#98fb98
paleturquoise175, 238, 238#afeeee
palevioletred219, 112, 147#db7093
papayawhip255, 239, 213#ffefd5
peachpuff255, 218, 185#ffdab9
peru205, 133, 63#cd853f
pink255, 192, 203#ffc0cb
plum221, 160, 221#dda0dd
powderblue176, 224, 230#b0e0e6
purple128, 0, 128#800080
red255, 0, 0#ff0000
rosybrown188, 143, 143#bc8f8f
royalblue65, 105, 225#4169e1
saddlebrown139, 69, 19#8b4513
salmon250, 128, 114#fa8072
sandybrown244, 164, 96#f4a460
seagreen46, 139, 87#2e8b57
seashell255, 245, 238#fff5ee
sienna160, 82, 45#a0522d
silver192, 192, 192#c0c0c0
skyblue135, 206, 235#87ceeb
slateblue106, 90, 205#6a5acd
slategray112, 128, 144#708090
slategrey112, 128, 144#708090
snow255, 250, 250#fffafa
springgreen0, 255, 127#00ff7f
steelblue70, 130, 180#4682b4
tan210, 180, 140#d2b48c
teal0, 128, 128#008080
thistle216, 191, 216#d8bfd8
tomato255, 99, 71#ff6347
turquoise64, 224, 208#40e0d0
violet238, 130, 238#ee82ee
wheat245, 222, 179#f5deb3
white255, 255, 255#ffffff
whitesmoke245, 245, 245#f5f5f5
yellow255, 255, 0#ffff00
yellowgreen154, 205, 50#9acd32
ColourTools.namedColours.blue // [0, 0, 255]
ColourTools.namedColours.red // [255, 0, 0]
ColourTools.namedColours.green // [0, 255, 0]

ColourTools.namedColours.azure // [240, 255, 255]
ColourTools.namedColours.darkorange // [255, 140, 0]
ColourTools.namedColours.dodgerblue // [30, 144, 255]

[↑ Back to ColourTools ↑]

parse

ColourTools.parse(input: string): ColourValues

Parse a string into a colour object (RGB array) Not extensive. Currently limited to:

  • 3 char hexes
  • 6 char hexes
  • comma separated RGB values
  • named colours (from namedColours dictionary)
ColourTools.parse('#FF0000') // [255, 0, 0]
ColourTools.parse('rgb(255, 0, 0)') // [255, 0, 0]
ColourTools.parse('red') // [255, 0, 0]
#Parameter NameRequiredType
0inputYesstring
Return Type
ColourValues

[↑ Back to ColourTools ↑]

toHex

ColourTools.toHex(colour: ColourValues): string

Convert a colour object (RGB array) to a hex string

ColourTools.toHex([255, 0, 0]) // '#FF0000'
#Parameter NameRequiredType
0colourYesColourValues
Return Type
string

[↑ Back to ColourTools ↑]

getLuminance

ColourTools.getLuminance(rgb: ColourValues): number

IMPORTANT: This is not the same as the HSL lightness value.

Get the luminance value of a given colour.

Between 0 and 255. Calculated using the formula: (RED × 0.299) + (GREEN × 0.587) + (BLUE × 0.114)

Is the Y (Luma) component of the YUV444 color model.

ColourTools.getLuminance([255, 0, 0]); // 76.245
ColourTools.getLuminance([0, 255, 0]); // 149.685
ColourTools.getLuminance([0, 0, 255]); // 29.07
#Parameter NameRequiredType
0rgbYesColourValues
Return Type
number

[↑ Back to ColourTools ↑]

toYUV

ColourTools.toYUV(rgb: ColourValues): ColourValues

Convert a colour object (RGB array) to a YUV array.

See https://en.wikipedia.org/wiki/YUV#Y%E2%80%B2UV444_to_RGB888_conversion

ColourTools.toYUV([255, 0, 0]); // [76.245, 112.439, -38.094]
#Parameter NameRequiredType
0rgbYesColourValues
Return Type
ColourValues

[↑ Back to ColourTools ↑]

toHSL

ColourTools.toHSL(colour: ColourValues, round: boolean): HSLValues

Convert a RGB array to a HSL array.

Adapted from https://www.30secondsofcode.org/js/s/rgb-to-hsl

ColourTools.toHSL([255, 0, 0]); // [0, 100, 50]
ColourTools.toHSL([0, 255, 0]); // [120, 100, 50]
#Parameter NameRequiredTypeDefault
0colourYesColourValues
1roundNobooleantrue
Return Type
HSLValues

[↑ Back to ColourTools ↑]

fromHSL

ColourTools.fromHSL(hsl: HSLValues, round: boolean): ColourValues

Convert a HSL array to a RGB array.

Adapted from https://www.30secondsofcode.org/js/s/hsl-to-rgb

ColourTools.fromHSL([0, 100, 50]); // [255, 0, 0]
ColourTools.fromHSL([120, 100, 50]); // [0, 255, 0]
#Parameter NameRequiredTypeDefault
0hslYesHSLValues
1roundNobooleantrue
Return Type
ColourValues

[↑ Back to ColourTools ↑]

invertColour

ColourTools.invertColour(rgb: ColourValues): ColourValues

Get the opposite colour of a given colour.

ColourTools.invertColour([255, 0, 0]); // [0, 255, 255]
ColourTools.invertColour([0, 255, 0]); // [ 255, 0, 255 ]
ColourTools.invertColour([0, 0, 255]); // [ 255, 255, 0 ]
#Parameter NameRequiredType
0rgbYesColourValues
Return Type
ColourValues

[↑ Back to ColourTools ↑]

getContrastedColour

ColourTools.getContrastedColour(colour: ColourValues): ColourValues

Get the colour that contrasts the most with a given colour. (White or black)

Returned colour can be used as a text colour on top of the provided colour

ColourTools.getContrastedColour([255, 0, 0]); // [255, 255, 255]
ColourTools.getContrastedColour([255, 255, 0]); // [0, 0, 0]
#Parameter NameRequiredType
0colourYesColourValues
Return Type
ColourValues

[↑ Back to ColourTools ↑]

getLimitedColour

ColourTools.getLimitedColour(colour: ColourValues, checkFn: (hsl: HSLValues) => boolean, adjustFn: (hsl: HSLValues) => HSLValues): ColourValues

Adjust a colour if a certain condition is met. Used for lightening/darkening colours that are too light/dark

All values in functions are HSL

ColourTools.getLimitedColour([255, 255, 255], ([h,s,l]) => l > 90, ([h,s,l]) => [h, s, 90]); // [ 230, 230, 230 ]
ColourTools.getLimitedColour([128, 128, 128], ([h,s,l]) => l > 90, ([h,s,l]) => [h, s, 90]); // [ 128, 128, 128 ]
#Parameter NameRequiredType
0colourYesColourValues
1checkFnYes(hsl: HSLValues) => boolean
2adjustFnYes(hsl: HSLValues) => HSLValues
Return Type
ColourValues

[↑ Back to ColourTools ↑]

TimeTools

A collection of time-related utility functions.

[↑ Back to top ↑]

toReadableDuration

TimeTools.toReadableDuration(duration: ms, longNames: boolean, maxUnits: number): string

Converts a duration in milliseconds to a human readable string.

TimeTools.toReadableDuration(20); // '20ms'
TimeTools.toReadableDuration(seconds(59)); // '59s'
TimeTools.toReadableDuration(seconds(60)); // '1m'
TimeTools.toReadableDuration(hours(23)); // '23h'
TimeTools.toReadableDuration(hours(24)); // '1d'
TimeTools.toReadableDuration(days(10)); // '10d'

TimeTools.toReadableDuration(20, true) // '20 milliseconds'
TimeTools.toReadableDuration(seconds(59), true) // '59 seconds'
TimeTools.toReadableDuration(seconds(60), true) // '1 minute'
TimeTools.toReadableDuration(hours(23), true) // '23 hours'
TimeTools.toReadableDuration(hours(24), true) // '1 day'
TimeTools.toReadableDuration(days(10), true) // '10 days'

const realisticDuration = days(10) + hours(2) + seconds(31) + 512; // 871231512
TimeTools.toReadableDuration(realisticDuration, true, 4) // '10 days, 2 hours, 31 seconds & 512 milliseconds'
TimeTools.toReadableDuration(realisticDuration, true) // '10 days, 2 hours & 31 seconds'
TimeTools.toReadableDuration(realisticDuration, true, 2) // '10 days & 2 hours'
#Parameter NameRequiredTypeDefault
0durationYesms
1longNamesNobooleanfalse
2maxUnitsNonumber3
Return Type
string

[↑ Back to TimeTools ↑]

ErrorTools

Functions for handling errors.

[↑ Back to top ↑]

tryOr

tryOr(orValue: T, func: (...args: A) => Promise<T>, ...args: A[]): Promise<T>
ErrorTools.tryOr(orValue: T, func: (...args: A) => Promise<T>, ...args: A[]): Promise<T>

Try to execute a function and return its result if it succeeds, or return the default value if it fails.

const result = tryOr('default', () => getSomething());
#Parameter NameRequiredType
0orValueYesT
1funcYes(...args: A) => Promise<T>
2…argsNoA[]
Return Type
Promise<T>

[↑ Back to ErrorTools ↑]

retry

retry(maxTries: number, delay: ms, suppress: boolean, run: (attemptNumber) => T): Promise<T>
ErrorTools.retry(maxTries: number, delay: ms, suppress: boolean, run: (attemptNumber) => T): Promise<T>

Try to execute a function and return its result if it succeeds, or retry a given number of times until it succeeds.

const result = tryOr(5, seconds(1), true, () => getSomething());
#Parameter NameRequiredTypeDefault
0maxTriesNonumber10
1delayNoms0
2suppressNobooleantrue
3runNo(attemptNumber) => Tfn.result(undefined as T)
Return Type
Promise<T>

[↑ Back to ErrorTools ↑]

retryOr

retryOr(orValue: T, maxTries: number, delay: ms, run: () => T | Promise<T>): Promise<T>
ErrorTools.retryOr(orValue: T, maxTries: number, delay: ms, run: () => T | Promise<T>): Promise<T>

Combination of retry and tryOr.

Try to execute a function and return its result if it succeeds, or retry a given number of times until it succeeds. Return the default value if it fails too many times

const result = retryOr('default', 5, seconds(1), () => getSomething());
#Parameter NameRequiredTypeDefault
0orValueYesT
1maxTriesNonumber10
2delayNoms0
3runNo() => T | Promise<T>fn.result(orValue)
Return Type
Promise<T>

[↑ Back to ErrorTools ↑]

progressBar

A progress bar that can be used in the terminal.

NOTE: This is eventually be moved to swiss-node

[↑ Back to top ↑]

Progress Bar

getProgressBar
getProgressBar(max: number, options: progressBar.ProgressBarOptions): ProgressBar
progressBar.getProgressBar(max: number, options: progressBar.ProgressBarOptions): ProgressBar

Usage:

import chalk from 'chalk'
import {getProgressBar} from 'swiss-ak';

console.log('-'.repeat(20) + ' < 20 Chars');

const progress = getProgressBar(5, {
  prefix: 'ABC',
  maxWidth: 20,
  chalk,
  wrapperFn: chalk.green
});
for (let i = 1; i <= 5; i++) {
  progress.set(i);
}
progress.finish();

Output:

-------------------- < 20 Chars
ABC ▕      ▏ [0 / 5]
ABC ▕█     ▏ [1 / 5]
ABC ▕██    ▏ [2 / 5]
ABC ▕████  ▏ [3 / 5]
ABC ▕█████ ▏ [4 / 5]
ABC ▕██████▏ [5 / 5]
#Parameter NameRequiredTypeDefault
0maxNonumber
1optionsNoprogressBar.ProgressBarOptions{}
Return Type
ProgressBar

[↑ Back to progressBar ↑]

getBar
getProgressBar().getBar(applyWrap: boolean): string

Get the output string of the progress bar

#Parameter NameRequiredTypeDefaultDescription
0applyWrapNobooleanfalseWhether or not to apply the wrapperFn to the output
Return Type
stringoutput string

[↑ Back to progressBar ↑]

update
getProgressBar().update(): string

Trigger the progress bar to update/rerender

Return Type
stringoutput string

[↑ Back to progressBar ↑]

next
getProgressBar().next(): string

Set the progress bar to the next value

Return Type
stringoutput string

[↑ Back to progressBar ↑]

set
getProgressBar().set(newCurrent: number): string

Set the progress bar to a specific value

#Parameter NameRequiredType
0newCurrentYesnumber
Return Type
stringoutput string

[↑ Back to progressBar ↑]

reset
getProgressBar().reset(): string

Set the progress bar to 0

Return Type
stringoutput string

[↑ Back to progressBar ↑]

start
getProgressBar().start(): string

Start displaying the progress bar

Return Type
stringoutput string

[↑ Back to progressBar ↑]

finish
getProgressBar().finish(): string

Stop displaying the progress bar

Return Type
stringoutput string

[↑ Back to progressBar ↑]

max
getProgressBar().max;

Readonly number value of the max value (provided to getProgressBar as first argument)

[↑ Back to progressBar ↑]

Options
progressBar.ProgressBarOptions;

All options are optional.

PropertyDefaultDescription
prefix''String to show to left of progress bar
prefixWidth0Min width of prefix - 10 => Example˽˽˽
maxPrefixWidthInfinityMax width of prefix
maxWidthprocess.stdout.columns or 100The maximum width the entire string may extend
wrapperFnnothingFunction to wrap the printed string (eg chalk.cyan)
barWrapFnnothingFunction to wrap the bar
barProgWrapFnnothingFunction to wrap the 'complete' segment of the bar
barCurrentWrapFnnothingFunction to wrap the 'current' segment of the bar
barEmptyWrapFnnothingFunction to wrap the empty/track part of the line
prefixWrapFnnothingFunction to wrap the prefix
countWrapFnnothingFunction to wrap the count
percentWrapFnnothingFunction to wrap the percent
showCounttrueShow numerical values of the count - [11 / 15]
showPercentfalseShow percentage completed - ( 69%)
countWidth0Min width of nums for showCount - 3 => [˽˽1 / ˽15]
progChar'█'Character to use for progress section of bar
emptyChar' 'Character to use for empty (rail) section of bar
startChar'▕'Character to start the progress bar with
endChar'▏'Character to end the progress bar with
showCurrentfalseShow the 'current' segment of the bar seperately
currentChar'▞'Character to use the the 'current' segment
printtrueWhether or not to print/output/log the progress bar
printFnprogressBar.utils.printLnFunction to use to print the progress bar

[↑ Back to progressBar ↑]

getFullOptions
progressBar.getFullOptions(opts: ProgressBarOptions): ProgressBarOptionsFull

Fill in any missing Progress Bar options with defaults.

Not needed for getProgressBar as it calls this internally.

progressBar.getFullOptions({});
// {
//   prefix: "",
//   prefixWidth: 0,
//   maxPrefixWidth: Infinity,
//   maxWidth: 214,
//   wrapperFn: [Function],
//   barWrapFn: [Function],
//   barProgWrapFn: [Function],
//   barCurrentWrapFn: [Function],
//   barEmptyWrapFn: [Function],
//   prefixWrapFn: [Function],
//   countWrapFn: [Function],
//   percentWrapFn: [Function],
//   showCount: true,
//   showPercent: false,
//   countWidth: 0,
//   progChar: "█",
//   emptyChar: " ",
//   startChar: "▕",
//   endChar: "▏",
//   showCurrent: false,
//   currentChar: "▞",
//   print: true,
//   printFn: [Function],
// }
#Parameter NameRequiredTypeDefault
0optsNoProgressBarOptions{}
Return Type
ProgressBarOptionsFull

[↑ Back to progressBar ↑]

Multi-Bar Manager

getMultiBarManager
getMultiBarManager(options: progressBar.MultiBarManagerOptions): MultiBarManager
progressBar.getMultiBarManager(options: progressBar.MultiBarManagerOptions): MultiBarManager

Returns a manager for multiple progress bars.

const manager = getMultiBarManager({});

const bar1 = manager.addNew(100, { prefix: 'Bar 1' });
const bar2 = manager.addNew(100, { prefix: 'Bar 2' });
const bar3 = manager.addNew(100, { prefix: 'Bar 3' });

bar1.set(25);
bar2.set(50);
bar3.set(75);

// Bar 1▕██████████████                                          ▏ [ 25 / 100]
// Bar 2▕████████████████████████████                            ▏ [ 50 / 100]
// Bar 3▕██████████████████████████████████████████              ▏ [ 75 / 100]
#Parameter NameRequiredTypeDefault
0optionsNoprogressBar.MultiBarManagerOptions{}
Return Type
MultiBarManager

[↑ Back to progressBar ↑]

add
getMultiBarManager().add(bar: ProgressBar, removeWhenFinished: boolean): void

Add a given progress bar to the manager

const manager = getMultiBarManager({ overrideOptions: { maxWidth: 75 } });

const bar1 = getProgressBar(100, { prefix: 'Bar 1' });
manager.add(bar1);
const bar2 = getProgressBar(100, { prefix: 'Bar 2' });
manager.add(bar2);
const bar3 = getProgressBar(100, { prefix: 'Bar 3' });
manager.add(bar3);

bar1.set(25);
bar2.set(50);
bar3.set(75);

// Bar 1▕██████████████                                          ▏ [ 25 / 100]
// Bar 2▕████████████████████████████                            ▏ [ 50 / 100]
// Bar 3▕██████████████████████████████████████████              ▏ [ 75 / 100]
#Parameter NameRequiredTypeDefault
0barYesProgressBar
1removeWhenFinishedNobooleanopts.removeFinished
Return Type
void

[↑ Back to progressBar ↑]

addNew
getMultiBarManager().addNew(max: number, options: progressBar.ProgressBarOptions): ProgressBar

Create a new progress bar and add it to the manager

const manager = getMultiBarManager({});

const bar1 = manager.addNew(100, { prefix: 'Bar 1' });
const bar2 = manager.addNew(100, { prefix: 'Bar 2' });
const bar3 = manager.addNew(100, { prefix: 'Bar 3' });

bar1.set(25);
bar2.set(50);
bar3.set(75);

// Bar 1▕██████████████                                          ▏ [ 25 / 100]
// Bar 2▕████████████████████████████                            ▏ [ 50 / 100]
// Bar 3▕██████████████████████████████████████████              ▏ [ 75 / 100]
#Parameter NameRequiredTypeDefault
0maxNonumber
1optionsNoprogressBar.ProgressBarOptions{}
Return Type
ProgressBar

[↑ Back to progressBar ↑]

remove
getMultiBarManager().remove(bar: ProgressBar): void

Remove a given progress bar from the manager

const manager = getMultiBarManager({ overrideOptions: { maxWidth: 75 } });

const bar1 = manager.addNew(100, { prefix: 'Bar 1' });
const bar2 = manager.addNew(100, { prefix: 'Bar 2' });
const bar3 = manager.addNew(100, { prefix: 'Bar 3' });

bar1.set(25);
bar2.set(50);
bar3.set(75);

manager.remove(bar2);

// Bar 1▕██████████████                                          ▏ [ 25 / 100]
// Bar 3▕██████████████████████████████████████████              ▏ [ 75 / 100]
#Parameter NameRequiredType
0barYesProgressBar
Return Type
void

[↑ Back to progressBar ↑]

update
getMultiBarManager().update(): void

Re-render the progress bars

const manager = getMultiBarManager({ overrideOptions: { maxWidth: 75 } });

const bar1 = manager.addNew(100, { prefix: 'Bar 1' });
const bar2 = manager.addNew(100, { prefix: 'Bar 2' });

bar1.set(25);
bar2.set(50);

manager.update();

// Bar 1▕██████████████                                          ▏ [ 25 / 100]
// Bar 2▕████████████████████████████                            ▏ [ 50 / 100]
Return Type
void

[↑ Back to progressBar ↑]

getBars
getMultiBarManager().getBars(): ProgressBar[]

Get an array of all the progress bars currently managed by the manager

const manager = getMultiBarManager({ overrideOptions: { maxWidth: 75 } });

const bar1 = manager.addNew(100, { prefix: 'Bar 1' });
const bar2 = manager.addNew(100, { prefix: 'Bar 2' });
const bar3 = manager.addNew(100, { prefix: 'Bar 3' });

bar1.set(25);
bar2.set(50);
bar3.set(75);

console.log(manager.getBars()); // [ bar1, bar2, bar3 ]

manager.remove(bar2);

console.log(manager.getBars()); // [ bar1, bar3 ]
Return Type
ProgressBar[]

[↑ Back to progressBar ↑]

Options
progressBar.MultiBarManagerOptions;

The options for MultiBar Managers

All options are optional.

PropertyDefaultDescription
numSlotsundefinedShorthand for setting both minSlots and maxSlots
minSlots0The min number of lines to print at a time
maxSlotsInfinityThe max number of lines to print at a time
removeFinishedfalseRemove progress bars from the manager when they finish
alignBottomfalseAlign the bars to the bottom of the print space
overrideOptions{} (No overrides)Override the options of the progress bars
variableOptions{} (No variable options)Override options differently for each bar
printtrueWhether or not to print the bars
printFnprogressBar.utils.multiPrintFnThe function to use to print the bars

[↑ Back to progressBar ↑]

getFullMultiBarManagerOptions
progressBar.getFullMultiBarManagerOptions(opts: MultiBarManagerOptions): MultiBarManagerOptionsFull

Fill in any missing MultiBar Manager options with defaults.

Not needed for getMultiBarManager as it calls this internally.

progressBar.getFullMultiBarManagerOptions({});
// {
//   numSlots: null,
//   minSlots: 0,
//   maxSlots: Infinity,
//   removeFinished: false,
//   alignBottom: false,
//   overrideOptions: {},
//   variableOptions: {},
//   print: true,
//   printFn: [Function],
// }
#Parameter NameRequiredType
0optsYesMultiBarManagerOptions
Return Type
MultiBarManagerOptionsFull

[↑ Back to progressBar ↑]

utils

progressBar.utils;

Small helper functions may help when using progress bars

[↑ Back to progressBar ↑]

printLn
progressBar.printLn(...text: any[]): void

Can use instead of console.log

Overwrites the previous line if possible (i.e. node);

Usage

import { printLn } from 'swiss-ak';

printLn('A');
printLn('B'); // Replaces the 'A' line
printLn('C'); // Replaces the 'B' line
printLn(); // Jumps a line
printLn('D'); // Replaces the empty line

Output

C
D
#Parameter NameRequiredType
0…textNoany[]
Return Type
void

[↑ Back to progressBar ↑]

multiPrintFn

The default printFn for MultiBarManagers

Clears previously printed lines and prints the output in their place

#Parameter NameRequiredType
0previousDrawnLinesYesnumber
1outputYesstring
Return Type
void

[↑ Back to progressBar ↑]

Cachier

A simple caching tool to store and retrieve values by id.

Useful for storing values that are expensive to calculate, or that you want to reuse.

[↑ Back to top ↑]

cachier

cachier;

A generic cachier object for general purpose caching.

Call cachier.create<T>() to create a new isolated cachier object with a specific type.

// Initial save
cachier.save('foo', { name: 'foo' }); // { "name": "foo" }
cachier.get('foo'); // { "name": "foo" }

// Overwrite
cachier.save('foo', { name: 'bar' }); // { "name": "bar" }
cachier.get('foo'); // { "name": "bar" }

// Get if exists, otherwise save
cachier.getOrSave('foo', { name: 'baz' }); // { "name": "bar" }
cachier.get('foo'); // { "name": "bar" }

// Get if exists, otherwise run function to create and save
cachier.getOrRun('foo', () => ({ name: 'qux' })); // { "name": "bar" }
cachier.get('foo'); // { "name": "bar" }

// Remove
cachier.remove('foo');
cachier.get('foo'); // undefined

// Populate
cachier.save('foo', { name: 'foo' }); // { "name": "foo" }
cachier.save('bar', { name: 'bar' }); // { "name": "bar" }
cachier.save('baz', { name: 'baz' }); // { "name": "baz" }

// Get all
cachier.getAll(); // { "foo": { "name": "foo" }, "bar": { "name": "bar" }, "baz": { "name": "baz" } }

// Clear
cachier.clear();
cachier.getAll(); // {}

[↑ Back to Cachier ↑]

get
cachier.get(id: string): T
cachier.create().get(id: string): T

Get a cached item by id.

cachier.save('foo', { name: 'foo' });
cachier.get('foo'); // { "name": "foo" }
#Parameter NameRequiredType
0idYesstring
Return Type
T

[↑ Back to Cachier ↑]

getOrSave
cachier.getOrSave(id: string, orValue: T): T
cachier.create().getOrSave(id: string, orValue: T): T

Get a cached item by id, or save a new item if it doesn't exist.

cachier.getOrSave('foo', { name: 'lorem' }); // { "name": "lorem" }
cachier.get('foo'); // { "name": "lorem" }

cachier.getOrSave('foo', { name: 'SOMETHING DIFFERENT' }); // { "name": "lorem" }
cachier.get('foo'); // { "name": "lorem" }
#Parameter NameRequiredType
0idYesstring
1orValueYesT
Return Type
T

[↑ Back to Cachier ↑]

getOrRun
cachier.getOrRun(id: string, orFunc: (id?: string) => T): T
cachier.create().getOrRun(id: string, orFunc: (id?: string) => T): T

Get a cached item by id, or run a function to create a new item if it doesn't exist.

The created item will be cached and returned.

cachier.getOrRun('foo', () => ({ name: 'lorem' })); // { "name": "lorem" }
cachier.get('foo'); // { "name": "lorem" }

cachier.getOrRun('foo', () => ({ name: 'SOMETHING DIFFERENT' })); // { "name": "lorem" }
cachier.get('foo'); // { "name": "lorem" }
#Parameter NameRequiredType
0idYesstring
1orFuncYes(id?: string) => T
Return Type
T

[↑ Back to Cachier ↑]

save
cachier.save(id: string, item: T): T
cachier.create().save(id: string, item: T): T

Save an item to the cache.

cachier.save('foo', { name: 'foo' }); // { "name": "foo" }
cachier.get('foo'); // { "name": "foo" }
#Parameter NameRequiredType
0idYesstring
1itemYesT
Return Type
T

[↑ Back to Cachier ↑]

remove
cachier.remove(id: string): void
cachier.create().remove(id: string): void

Remove an item from the cache.

cachier.save('foo', { name: 'foo' });
cachier.get('foo'); // { "name": "foo" }

cachier.remove('foo');
cachier.get('foo'); // undefined
#Parameter NameRequiredType
0idYesstring
Return Type
void

[↑ Back to Cachier ↑]

clear
cachier.clear(): void
cachier.create().clear(): void

Clear all items from the cache.

cachier.save('foo', { name: 'foo' });
cachier.getAll(); // { foo: { "name": "foo" } }

cachier.clear();
cachier.getAll(); // {}
Return Type
void

[↑ Back to Cachier ↑]

getAll
cachier.getAll(): ObjOfType<T>
cachier.create().getAll(): ObjOfType<T>

Get all items from the cache.

cachier.save('foo', { name: 'foo' });
cachier.save('bar', { name: 'bar' });
cachier.save('baz', { name: 'baz' });

cachier.getAll(); // { "foo": { "name": "foo" }, "bar": { "name": "bar" }, "baz": { "name": "baz" } }
Return Type
ObjOfType<T>

[↑ Back to Cachier ↑]

create
cachier.create<T>(): Cachier<U>
cachier.create().create<T>(): Cachier<U>

Create a new isolated cachier object with a specific type.

const numCache = cachier.create<number>();

numCache.save('bar', 123);
cachier.save('foo', { name: 'foo' });

numCache.getAll(); // { "bar": 123 }
cachier.getAll(); // { "foo": { "name": "foo" } }
Return Type
Cachier<U>

[↑ Back to Cachier ↑]

Cachier

Cachier<T>;

Type for a cachier object.

[↑ Back to Cachier ↑]

symbols

symbols;

A series of characters that can be used for display symbols

NameSymbol
TABsymbols.TAB
TICKsymbols.TICK
CROSSsymbols.CROSS
PLUSsymbols.PLUS+
MINUSsymbols.MINUS-
TIMESsymbols.TIMES×
DIVIDEsymbols.DIVIDE÷
ELLIPSISsymbols.ELLIPSIS
BULLETsymbols.BULLET
EJECTsymbols.EJECT
TILDEsymbols.TILDE~
HOMEsymbols.HOME~
RADIO_EMPTYsymbols.RADIO_EMPTY
RADIO_FULLsymbols.RADIO_FULL
CURSORsymbols.CURSOR
CHEV_LFTsymbols.CHEV_LFT
CHEV_RGTsymbols.CHEV_RGT
CHAINsymbols.CHAIN
TRI_UPPsymbols.TRI_UPP
TRI_DWNsymbols.TRI_DWN
TRI_RGTsymbols.TRI_RGT
TRI_LFTsymbols.TRI_LFT
ARROW_UPPsymbols.ARROW_UPP
ARROW_DWNsymbols.ARROW_DWN
ARROW_RGTsymbols.ARROW_RGT
ARROW_LFTsymbols.ARROW_LFT
ARROW_UPP_RGTsymbols.ARROW_UPP_RGT
ARROW_DWN_RGTsymbols.ARROW_DWN_RGT
ARROW_DWN_LFTsymbols.ARROW_DWN_LFT
ARROW_UPP_LFTsymbols.ARROW_UPP_LFT
ARROW_STILLsymbols.ARROW_STILL
ARROW_FLIP_Hsymbols.ARROW_FLIP_H
ARROW_FLIP_Vsymbols.ARROW_FLIP_V
ARROW_ROTATE_UPPsymbols.ARROW_ROTATE_UPP
ARROW_ROTATE_DWNsymbols.ARROW_ROTATE_DWN
ARROW_ROTATE_LFTsymbols.ARROW_ROTATE_LFT
ARROW_ROTATE_RGTsymbols.ARROW_ROTATE_RGT
ARROW_ROTATE_CLOCKsymbols.ARROW_ROTATE_CLOCK
ARROW_ROTATE_ANTI_CLOCKsymbols.ARROW_ROTATE_ANTI_CLOCK
FRACTION_1_4symbols.FRACTION_1_4¼
FRACTION_1_2symbols.FRACTION_1_2½
FRACTION_3_4symbols.FRACTION_3_4¾
SUPERSCRIPTsymbols.SUPERSCRIPT['1']¹
symbols.SUPERSCRIPT['2']²
symbols.SUPERSCRIPT['3']³
symbols.SUPERSCRIPT['4']
symbols.SUPERSCRIPT['5']
symbols.SUPERSCRIPT['6']
symbols.SUPERSCRIPT['7']
symbols.SUPERSCRIPT['8']
symbols.SUPERSCRIPT['9']
symbols.SUPERSCRIPT['0']
symbols.SUPERSCRIPT['-']
symbols.SUPERSCRIPT['+']
symbols.SUPERSCRIPT['=']
symbols.SUPERSCRIPT['(']
symbols.SUPERSCRIPT[')']
symbols.SUPERSCRIPT['i']
symbols.SUPERSCRIPT['n']
symbols.SUPERSCRIPT['o']°
symbols.SUPERSCRIPT['*']°

[↑ Back to top ↑]

superscript

superscript(num: number | string): string

Converts a string or number to superscript (where possible)

Known superscript characters: ¹²³⁴⁵⁶⁷⁸⁹⁰⁻⁺⁼⁽⁾ⁱⁿ°

Characters without a superscript equivalent will be replaced with a °

superscript(219) // '²¹⁹'
superscript(1234567890) // '¹²³⁴⁵⁶⁷⁸⁹⁰'
#Parameter NameRequiredType
0numYesnumber | string
Return Type
string

[↑ Back to symbols ↑]

queue

A way of managing queues from different parts of the code.

[↑ Back to top ↑]

QueueManager

QueueManager;

Allows you to queue up functions to be executed in order.

Importantly, it allows you to add to the queue from another part of the code, without needing to access a promise directly.

const printDocument = async (id: number) => {
  // do something
  await wait(seconds(5));
}

const queue = new QueueManager();

const start = Date.now();

// happening async/concurrently
PromiseTools.each(range(5), async (i) => {
  await wait(seconds(Math.random() * 1));
  console.log(Date.now() - start, ' - trigger:', i, );
  await queue.add('printer', () => printDocument(i))
  console.log(Date.now() - start, ' - printed:', i);
})

// Output:

// 184 ' - trigger:' 0
// 355 ' - trigger:' 2
// 435 ' - trigger:' 4
// 448 ' - trigger:' 1
// 487 ' - trigger:' 3
// 5190 ' - printed:' 0
// 10195 ' - printed:' 2
// 15200 ' - printed:' 4
// 20205 ' - printed:' 1
// 25208 ' - printed:' 3

[↑ Back to queue ↑]

setDefaultPauseTime
queue.setDefaultPauseTime(time: ms): void
new QueueManager().setDefaultPauseTime(time: ms): void

Sets the default pause time for pauses between queue items.

#Parameter NameRequiredType
0timeYesms
Return Type
void

[↑ Back to queue ↑]

setPauseTime
queue.setPauseTime(id: string, time: ms): void
new QueueManager().setPauseTime(id: string, time: ms): void

Sets the pause time for pauses between queue items for the specified queue.

#Parameter NameRequiredType
0idYesstring
1timeYesms
Return Type
void

[↑ Back to queue ↑]

add
queue.add(id: string, promiseItem: PromiseTools.PromiseItem<T>): Promise<T>
new QueueManager().add(id: string, promiseItem: PromiseTools.PromiseItem<T>): Promise<T>

Adds a function to the queue.

#Parameter NameRequiredType
0idYesstring
1promiseItemYesPromiseTools.PromiseItem<T>
Return Type
Promise<T>

[↑ Back to queue ↑]

new
queue.new(defaultPauseTime: ms): QueueManager
new QueueManager().new(defaultPauseTime: ms): QueueManager
QueueManager.new(defaultPauseTime: ms): QueueManager

Creates a new QueueManager instance.

#Parameter NameRequiredTypeDefault
0defaultPauseTimeNoms0
Return Type
QueueManager

[↑ Back to queue ↑]

queue

queue;

An instance of QueueManager

See QueueManager for more information.

[↑ Back to queue ↑]

timer

A debug tool for measuring the duration of code blocks.

[↑ Back to top ↑]

Timer Instance

start
timer.start(...labels: string[]): void
getTimer().start(...labels: string[]): void

Start a timer

#Parameter NameRequiredType
0…labelsYesstring[]
Return Type
void

[↑ Back to timer ↑]

end
timer.end(...labels: string[]): void
getTimer().end(...labels: string[]): void

End a given timer

#Parameter NameRequiredType
0…labelsYesstring[]
Return Type
void

[↑ Back to timer ↑]

switch
timer.switch(endLabel: string | string[], startLabel: string | string[]): void
getTimer().switch(endLabel: string | string[], startLabel: string | string[]): void

Switch the timer The same as calling timer.end(endLabel) and timer.start(startLabel)

#Parameter NameRequiredType
0endLabelYesstring | string[]
1startLabelYesstring | string[]
Return Type
void

[↑ Back to timer ↑]

getTable
timer.getTable(prefix: string, customEntries: ((durations: TimerDurations<TName>) => CustomEntryObj)[] | CustomEntryDict<TimerDurations<TName>, TName>): string
getTimer().getTable(prefix: string, customEntries: ((durations: TimerDurations<TName>) => CustomEntryObj)[] | CustomEntryDict<TimerDurations<TName>, TName>): string

Get the timing table as a string

#Parameter NameRequiredType
0prefixNostring
1customEntriesNo((durations: TimerDurations<TName>) => CustomEntryObj)[] | CustomEntryDict<TimerDurations<TName>, TName>
Return Type
stringthe timing table

[↑ Back to timer ↑]

log
timer.log(prefix: string, customEntries: ((durations: TimerDurations<TName>) => CustomEntryObj)[] | CustomEntryDict<TimerDurations<TName>, TName>): number
getTimer().log(prefix: string, customEntries: ((durations: TimerDurations<TName>) => CustomEntryObj)[] | CustomEntryDict<TimerDurations<TName>, TName>): number

Log the timing table

#Parameter NameRequiredType
0prefixNostring
1customEntriesNo((durations: TimerDurations<TName>) => CustomEntryObj)[] | CustomEntryDict<TimerDurations<TName>, TName>
Return Type
numberthe number of lines logged

[↑ Back to timer ↑]

reset
timer.reset(): void
getTimer().reset(): void

Reset the timer

Return Type
void

[↑ Back to timer ↑]

getDuration
timer.getDuration(): ms
getTimer().getDuration(): ms

Get the duration of a given timer

Return Type
ms

[↑ Back to timer ↑]

names
timer.names;
getTimer().names;

The names of the timers

[↑ Back to timer ↑]

displayNames
timer.displayNames;
getTimer().displayNames;

The display names of the timers

[↑ Back to timer ↑]

startTimes
timer.startTimes;
getTimer().startTimes;

The start times of the timers

[↑ Back to timer ↑]

endTimes
timer.endTimes;
getTimer().endTimes;

The end times of the timers

[↑ Back to timer ↑]

getTimer

getTimer(name: string, verbose: boolean, wrapperFn: any, displayNames: TName): any

Usage:

const timer = getTimer('Example', false, colr.red, {
  TOTAL: 'TOTAL',
  INTRO: 'Action 1',
  ENDING: 'Action 2'
});
timer.start(timer.TOTAL, timer.INTRO);

await wait(seconds(4)); // do something async

timer.switch(timer.INTRO, timer.ENDING); // same as calling end(timer.INTRO) and start(timer.ENDING)

await wait(seconds(6)); // do something async

timer.end(timer.TOTAL, timer.ENDING);
timer.log();

Output:

Example Times:
	Action 1: 4s
	Action 2: 6s
	⎯⎯⎯⎯⎯⎯⎯
	TOTAL:    10s
#Parameter NameRequiredTypeDefault
0nameNostring
1verboseNobooleanfalse
2wrapperFnNoanycolr.dark.white
3displayNamesNoTName
Return Type
any

[↑ Back to timer ↑]

timer

timer;

Usage:

timer.start('TOTAL', 'Intro');

await wait(seconds(4)); // do something async

timer.switch('Intro', 'Ending'); // same as calling timer.end('Intro') and timer.start('Ending')

await wait(seconds(6)); // do something async

timer.end('TOTAL', 'Ending');
timer.log();

Output:

Times:
	Intro:   4s
	Ending:  6s
	⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
	TOTAL:   10s

[↑ Back to timer ↑]

safe

A series of simple functions for ensuring that a value is safe to use.

Used internally for input validation.

[↑ Back to top ↑]

num

safe.num(input: number, isInt: boolean, min: number, max: number, fallback: number): number

Process a number value, ensuring that it is safe to use.

safe.num(10); // 10
safe.num(10000); // 10000
safe.num(-1); // -1
safe.num(true); // 0
safe.num('123'); // 0
safe.num(NaN); // 0
safe.num(Infinity); // 0
safe.num(null); // 0
safe.num(undefined); // 0

safe.num(10, true, 0, 100, 99); // 10
safe.num(10000, true, 0, 100, 99); // 100
safe.num(-1, true, 0, 100, 99); // 0
safe.num(true, true, 0, 100, 99); // 99
safe.num('123', true, 0, 100, 99); // 99
safe.num(NaN, true, 0, 100, 99); // 99
safe.num(Infinity, true, 0, 100, 99); // 100
safe.num(null, true, 0, 100, 99); // 99
safe.num(undefined, true, 0, 100, 99); // 99
#Parameter NameRequiredTypeDefault
0inputYesnumber
1isIntNobooleanfalse
2minNonumber
3maxNonumber
4fallbackNonumber0
Return Type
number

[↑ Back to safe ↑]

str

safe.str(input: string, allowBasicStringify: boolean, fallback: string): string

Process a string value, ensuring that it is safe to use.

safe.str('foo'); // 'foo'
safe.str(''); // ''
safe.str(123); // ''
safe.str(true); // ''
safe.str({foo: 'bar'}); // ''
safe.str([]); // ''
safe.str(null); // ''
safe.str(undefined); // ''

safe.str('foo', true, 'bar'); // 'foo'
safe.str('', true, 'bar'); // ''
safe.str(123, true, 'bar'); // '123'
safe.str(true, true, 'bar'); // 'true'
safe.str({foo: 'bar'}, true, 'bar'); // 'bar'
safe.str([], true, 'bar'); // 'bar'
safe.str(null, true, 'bar'); // 'bar'
safe.str(undefined, true, 'bar'); // 'bar'
#Parameter NameRequiredTypeDefault
0inputYesstring
1allowBasicStringifyNobooleanfalse
2fallbackNostring''
Return Type
string

[↑ Back to safe ↑]

bool

safe.bool(input: boolean, fallback: boolean): boolean

Process a boolean value, ensuring that it is safe to use.

safe.bool(true); // true
safe.bool(false); // false
safe.bool(1); // true
safe.bool(0); // false
safe.bool(123); // false
safe.bool('true'); // true
safe.bool('false'); // false
safe.bool('foobar'); // false
safe.bool({foo: 'bar'}); // false
safe.bool([]); // false
safe.bool(null); // false
safe.bool(undefined); // false

safe.bool(true, true); // true
safe.bool(false, true); // false
safe.bool(1, true); // true
safe.bool(0, true); // false
safe.bool(123, true); // true
safe.bool('true', true); // true
safe.bool('false', true); // false
safe.bool('foobar', true); // true
safe.bool({foo: 'bar'}, true); // true
safe.bool([], true); // true
safe.bool(null, true); // true
safe.bool(undefined, true); // true

|  #  | Parameter Name | Required | Type      | Default |
|:---:|:---------------|:---------|:----------|:--------|
| *0* | `input`        | **Yes**  | `boolean` |         |
| *1* | `fallback`     | *No*     | `boolean` | `false` |

| Return Type |
|-------------|
| `boolean`   |

<p style="text-align: right" align="right"><a href="#safe"> [↑ Back to <b>safe</b> ↑] </a></p>

### <span id="safe_func">func</span>

```typescript
safe.func<T>(input: T, fallback: T): T

Process a function value, ensuring that it is safe to use.

safe.func((p: number) => 123); // (p: number) => 123
safe.func(true); // (() => {})
safe.func(false); // (() => {})
safe.func(123); // (() => {})
safe.func('foobar'); // (() => {})
safe.func({foo: 'bar'}); // (() => {})
safe.func([1, 2, 3]); // (() => {})
safe.func(null); // (() => {})
safe.func(undefined); // (() => {})

safe.func((p: number) => 123, (q: number) => 456); // (p: number) => 123
safe.func(true, (q: number) => 456); // (q: number) => 456
safe.func(false, (q: number) => 456); // (q: number) => 456
safe.func(123, (q: number) => 456); // (q: number) => 456
safe.func('foobar', (q: number) => 456); // (q: number) => 456
safe.func({foo: 'bar'}, (q: number) => 456); // (q: number) => 456
safe.func([1, 2, 3], (q: number) => 456); // (q: number) => 456
safe.func(null, (q: number) => 456); // (q: number) => 456
safe.func(undefined, (q: number) => 456); // (q: number) => 456
#Parameter NameRequiredTypeDefault
0inputYesT
1fallbackNoT(() => {}) as unknown as T
Return Type
T

[↑ Back to safe ↑]

obj

safe.obj<T>(input: T, allowArrays: boolean, fallback: T): T

Process an object value, ensuring that it is safe to use.

safe.obj({foo: 'bar'}); // {foo: 'bar'}
safe.obj([1, 2, 3]); // [1, 2, 3]
safe.obj(true); // {}
safe.obj(false); // {}
safe.obj(123); // {}
safe.obj('foobar'); // {}
safe.obj(null); // {}
safe.obj(undefined); // {}

safe.obj({foo: 'bar'}, true, {baz: 123}); // {foo: 'bar'}
safe.obj([1, 2, 3], true, {baz: 123}); // [1, 2, 3]
safe.obj(true, true, {baz: 123}); // {baz: 123}
safe.obj(false, true, {baz: 123}); // {baz: 123}
safe.obj(123, true, {baz: 123}); // {baz: 123}
safe.obj('foobar', true, {baz: 123}); // {baz: 123}
safe.obj(null, true, {baz: 123}); // {baz: 123}
safe.obj(undefined, true, {baz: 123}); // {baz: 123}
#Parameter NameRequiredTypeDefault
0inputYesT
1allowArraysNobooleanfalse
2fallbackNoT{} as T
Return Type
T

[↑ Back to safe ↑]

objWith

safe.objWith<T>(input: T, objConfig: ObjWithConfig<T>, allowComposition: boolean): T

Process an object value, ensuring that it is safe to use, and has the neccesary properties.

You must provide a config object that defines the properties that are required, and how to process them. Each required property must have a fallback value, and can have an optional checkFn and safeFn.

  • fallback - the value to use if the property is missing or invalid
  • checkFn - a function that returns true if the property is missing or invalid (defaults to (v) => v === undefined)
  • safeFn - a function that returns the safe value to use (defaults to (v, f) => f)
const config1: ObjWithConfig<{ foo: string }> = {
  foo: {
    fallback: 'a',
    safeFn: (v, f) => safe.str(v, false, f),
  },
};
safe.objWith({foo: 'bar'}, config1); // { foo: 'bar' }
safe.objWith([1, 2, 3], config1); // { '0': 1, '1': 2, '2': 3, foo: 'a' }
safe.objWith(true, config1); // { foo: 'a' }
safe.objWith(false, config1); // { foo: 'a' }
safe.objWith(123, config1); // { foo: 'a' }
safe.objWith('foobar', config1); // { foo: 'a' }
safe.objWith(null, config1); // { foo: 'a' }
safe.objWith(undefined, config1); // { foo: 'a' }

const config2: ObjWithConfig<{ foo: string; bar: number }> = {
  ...config1,
  bar: {
    fallback: 78,
    safeFn: (v, f) => safe.num(v, true, 0, 100, f),
  },
};
safe.objWith({foo: 'bar', bar: 45}, config2); // { foo: 'bar', bar: 45 }
safe.objWith([1, 2, 3], config2); // { '0': 1, '1': 2, '2': 3, foo: 'a', bar: 78 }
safe.objWith(true, config2); // { foo: 'a', bar: 78 }
safe.objWith(false, config2); // { foo: 'a', bar: 78 }
safe.objWith(123, config2); // { foo: 'a', bar: 78 }
safe.objWith('foobar', config2); // { foo: 'a', bar: 78 }
safe.objWith(null, config2); // { foo: 'a', bar: 78 }
safe.objWith(undefined, config2); // { foo: 'a', bar: 78 }
#Parameter NameRequiredTypeDefault
0inputYesT
1objConfigYesObjWithConfig<T>
2allowCompositionNobooleantrue
Return Type
T

[↑ Back to safe ↑]

arr

safe.arr<T>(input: T[], fallback: T[], minLength: number, maxLength: number): T[]

Process an array value, ensuring that it is safe to use.

safe.arr([1, 2, 3]); // [ 1, 2, 3 ]
safe.arr(true); // []
safe.arr(false); // []
safe.arr(123); // []
safe.arr('foobar'); // []
safe.arr({foo: 'bar'}); // []
safe.arr(null); // []
safe.arr(undefined); // []

safe.arr([1, 2, 3], [4, 5, 6]); // [ 1, 2, 3 ]
safe.arr(true, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arr(false, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arr(123, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arr('foobar', [4, 5, 6]); // [ 4, 5, 6 ]
safe.arr({foo: 'bar'}, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arr(null, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arr(undefined, [4, 5, 6]); // [ 4, 5, 6 ]
#Parameter NameRequiredTypeDefault
0inputYesT[]
1fallbackNoT[][]
2minLengthNonumber0
3maxLengthNonumberInfinity
Return Type
T[]

[↑ Back to safe ↑]

prop

safe.prop(input: string | number, fallback: string | number): string | number

Process a value (string or number) that is expected to be used as a property name, ensuring that it is safe to use.

Equivalent to typeof value === 'number' ? safe.num(value) : safe.str(value, true, '')

safe.prop('foo'); // 'foo'
safe.prop(''); // ''
safe.prop(123); // 123
safe.prop(true); // 'true'
safe.prop({foo: 'bar'}); // ''
safe.prop([]); // ''
safe.prop(null); // ''
safe.prop(undefined); // ''

safe.prop('foo', 'bar'); // 'foo'
safe.prop('', 'bar'); // ''
safe.prop(123, 'bar'); // 123
safe.prop(true, 'bar'); // 'true'
safe.prop({foo: 'bar'}, 'bar'); // 'bar'
safe.prop([], 'bar'); // 'bar'
safe.prop(null, 'bar'); // 'bar'
safe.prop(undefined, 'bar'); // 'bar'
#Parameter NameRequiredTypeDefault
0inputYesstring | number
1fallbackNostring | number''
Return Type
string | number

[↑ Back to safe ↑]

arrOf

A series of functions for processing arrays of values.

[↑ Back to safe ↑]

num
safe.arrOf.num(input: number[], isInt: boolean, min: number, max: number, fallback: number, fallbackArr: number[], arrMinLength: number, arrMaxLength: number): number[]

Process an array of numbers, ensuring that they are safe to use.

safe.arrOf.num([1, 2, 3]); // [ 1, 2, 3 ]
safe.arrOf.num(['foo', 1, true, null, undefined, [], {}]); // [ 0, 1, 0, 0, 0, 0, 0 ]
safe.arrOf.num(true); // []
safe.arrOf.num(false); // []
safe.arrOf.num(123); // []
safe.arrOf.num('foobar'); // []
safe.arrOf.num({foo: 'bar'}); // []
safe.arrOf.num(null); // []
safe.arrOf.num(undefined); // []

safe.arrOf.num([1, 2, 3], true, 0, 100, 99, [4, 5, 6]); // [ 1, 2, 3 ]
safe.arrOf.num(['foo', 1, true, null, undefined, [], {}], true, 0, 100, 99, [4, 5, 6]); // [ 99, 1, 99, 99, 99, 99, 99 ]
safe.arrOf.num(true, true, 0, 100, 99, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arrOf.num(false, true, 0, 100, 99, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arrOf.num(123, true, 0, 100, 99, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arrOf.num('foobar', true, 0, 100, 99, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arrOf.num({foo: 'bar'}, true, 0, 100, 99, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arrOf.num(null, true, 0, 100, 99, [4, 5, 6]); // [ 4, 5, 6 ]
safe.arrOf.num(undefined, true, 0, 100, 99, [4, 5, 6]); // [ 4, 5, 6 ]
#Parameter NameRequiredTypeDefault
0inputYesnumber[]
1isIntNobooleanfalse
2minNonumber
3maxNonumber
4fallbackNonumber
5fallbackArrNonumber[][]
6arrMinLengthNonumber0
7arrMaxLengthNonumberInfinity
Return Type
number[]

[↑ Back to safe ↑]

str
safe.arrOf.str(input: string[], allowStringify: boolean, fallback: string, fallbackArr: string[], arrMinLength: number, arrMaxLength: number): string[]

Process an array of strings, ensuring that they are safe to use.

safe.arrOf.str(['foo', 'bar', 'baz']); // [ 'foo', 'bar', 'baz' ]
safe.arrOf.str(['foo', 1, true, null, undefined, [], {}]); // [ 'foo', '', '', '', '', '', '' ]
safe.arrOf.str(true); // []
safe.arrOf.str(false); // []
safe.arrOf.str(123); // []
safe.arrOf.str('foobar'); // []
safe.arrOf.str({foo: 'bar'}); // []
safe.arrOf.str(null); // []
safe.arrOf.str(undefined); // []

safe.arrOf.str(['foo', 'bar', 'baz'], true, 'LOREM', ['IPSUM']); // [ 'foo', 'bar', 'baz' ]
safe.arrOf.str(['foo', 1, true, null, undefined, [], {}], true, 'LOREM', ['IPSUM']); // [ 'foo', '1', 'true', 'LOREM', 'LOREM', 'LOREM', 'LOREM' ]
safe.arrOf.str(true, true, 'LOREM', ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.str(false, true, 'LOREM', ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.str(123, true, 'LOREM', ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.str('foobar', true, 'LOREM', ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.str({foo: 'bar'}, true, 'LOREM', ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.str(null, true, 'LOREM', ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.str(undefined, true, 'LOREM', ['IPSUM']); // [ 'IPSUM' ]
#Parameter NameRequiredTypeDefault
0inputYesstring[]
1allowStringifyNobooleanfalse
2fallbackNostring
3fallbackArrNostring[][]
4arrMinLengthNonumber0
5arrMaxLengthNonumberInfinity
Return Type
string[]

[↑ Back to safe ↑]

bool
safe.arrOf.bool(input: boolean[], fallback: boolean, fallbackArr: boolean[], arrMinLength: number, arrMaxLength: number): boolean[]

Process an array of booleans, ensuring that they are safe to use.

safe.arrOf.bool([false, true, false]); // [ false, true, false ]
safe.arrOf.bool(['foo', 123, true, null, undefined, [], {}]); // [ false, false, true, false, false, false, false ]
safe.arrOf.bool(true); // []
safe.arrOf.bool(false); // []
safe.arrOf.bool(123); // []
safe.arrOf.bool('foobar'); // []
safe.arrOf.bool({foo: 'bar'}); // []
safe.arrOf.bool(null); // []
safe.arrOf.bool(undefined); // []

safe.arrOf.bool([false, true, false], true, [true, true]); // [ false, true, false ]
safe.arrOf.bool(['foo', 123, true, null, undefined, [], {}], true, [true, true]); // [ true, true, true, true, true, true, true ]
safe.arrOf.bool(true, true, [true, true]); // [ true, true ]
safe.arrOf.bool(false, true, [true, true]); // [ true, true ]
safe.arrOf.bool(123, true, [true, true]); // [ true, true ]
safe.arrOf.bool('foobar', true, [true, true]); // [ true, true ]
safe.arrOf.bool({foo: 'bar'}, true, [true, true]); // [ true, true ]
safe.arrOf.bool(null, true, [true, true]); // [ true, true ]
safe.arrOf.bool(undefined, true, [true, true]); // [ true, true ]
#Parameter NameRequiredTypeDefault
0inputYesboolean[]
1fallbackNoboolean
2fallbackArrNoboolean[][]
3arrMinLengthNonumber0
4arrMaxLengthNonumberInfinity
Return Type
boolean[]

[↑ Back to safe ↑]

func
safe.arrOf.func<T>(input: T[], fallback: T, fallbackArr: T[], arrMinLength: number, arrMaxLength: number): T[]

Process an array of functions, ensuring that they are safe to use.

safe.arrOf.func([(p) => 1]); // [(p) => 1]
safe.arrOf.func(['foo', 1, true, null, undefined, [], {}]); // [() => {}, () => {}, () => {}, () => {}, () => {}, () => {}, () => {}]
safe.arrOf.func(true); // []
safe.arrOf.func(false); // []
safe.arrOf.func(123); // []
safe.arrOf.func('foobar'); // []
safe.arrOf.func({foo: 'bar'}); // []
safe.arrOf.func(null); // []
safe.arrOf.func(undefined); // []

safe.arrOf.func([(p) => 1], (q) => 2, [(r) => 3]); // [(p) => 1]
safe.arrOf.func(['foo', 1, true, null, undefined, [], {}], (q) => 2, [(r) => 3]); // [(q) => 2, (q) => 2, (q) => 2, (q) => 2, (q) => 2, (q) => 2, (q) => 2]
safe.arrOf.func(true, (q) => 2, [(r) => 3]); //  [(r) => 3]
safe.arrOf.func(false, (q) => 2, [(r) => 3]); //  [(r) => 3]
safe.arrOf.func(123, (q) => 2, [(r) => 3]); //  [(r) => 3]
safe.arrOf.func('foobar', (q) => 2, [(r) => 3]); //  [(r) => 3]
safe.arrOf.func({foo: 'bar'}, (q) => 2, [(r) => 3]); //  [(r) => 3]
safe.arrOf.func(null, (q) => 2, [(r) => 3]); //  [(r) => 3]
safe.arrOf.func(undefined, (q) => 2, [(r) => 3]); //  [(r) => 3]
#Parameter NameRequiredTypeDefault
0inputYesT[]
1fallbackNoT
2fallbackArrNoT[][]
3arrMinLengthNonumber0
4arrMaxLengthNonumberInfinity
Return Type
T[]

[↑ Back to safe ↑]

obj
safe.arrOf.obj<T>(input: T[], allowArrays: boolean, fallback: T, fallbackArr: T[], arrMinLength: number, arrMaxLength: number): T[]

Process an array of objects, ensuring that they are safe to use.

safe.arrOf.obj([{foo: 1}, {bar: 2}]); // [ { foo: 1 }, { bar: 2 } ]
safe.arrOf.obj(['foo', 1, true, null, undefined, [], {}]); // [ {}, {}, {}, {}, {}, [], {} ]
safe.arrOf.obj(true); // []
safe.arrOf.obj(false); // []
safe.arrOf.obj(123); // []
safe.arrOf.obj('foobar'); // []
safe.arrOf.obj({foo: 'bar'}); // []
safe.arrOf.obj(null); // []
safe.arrOf.obj(undefined); // []

safe.arrOf.obj([{foo: 1}, {bar: 2}], true, {l: 3}, [{i: 4}]); // [ { foo: 1 }, { bar: 2 } ]
safe.arrOf.obj(['foo', 1, true, null, undefined, [], {}], true, {l: 3}, [{i: 4}]); // [ { l: 3 }, { l: 3 }, { l: 3 }, { l: 3 }, { l: 3 }, [], { } ]
safe.arrOf.obj(true, true, {l: 3}, [{i: 4}]); // [ { i: 4 } ]
safe.arrOf.obj(false, true, {l: 3}, [{i: 4}]); // [ { i: 4 } ]
safe.arrOf.obj(123, true, {l: 3}, [{i: 4}]); // [ { i: 4 } ]
safe.arrOf.obj('foobar', true, {l: 3}, [{i: 4}]); // [ { i: 4 } ]
safe.arrOf.obj({foo: 'bar'}, true, {l: 3}, [{i: 4}]); // [ { i: 4 } ]
safe.arrOf.obj(null, true, {l: 3}, [{i: 4}]); // [ { i: 4 } ]
safe.arrOf.obj(undefined, true, {l: 3}, [{i: 4}]); // [ { i: 4 } ]
#Parameter NameRequiredTypeDefault
0inputYesT[]
1allowArraysNobooleanfalse
2fallbackNoT
3fallbackArrNoT[][]
4arrMinLengthNonumber0
5arrMaxLengthNonumberInfinity
Return Type
T[]

[↑ Back to safe ↑]

objWith
safe.arrOf.objWith<T>(input: T[], objConfig: ObjWithConfig<T>, allowComposition: boolean, fallbackArr: T[], arrMinLength: number, arrMaxLength: number): T[]

Process an array of objects, ensuring that they are safe to use, and have the neccesary properties.

const config1: ObjWithConfig<{ foo: string }> = {
  foo: {
    fallback: 'a',
    safeFn: (v, f) => safe.str(v, false, f)
  }
};
safe.arrOf.objWith([{ foo: 1 }, { bar: 2 }], config1); // [ { foo: 'a' }, { bar: 2, foo: 'a' } ]
safe.arrOf.objWith(['foo', 1, true, null, undefined, [], {}], config1); // [{ foo: 'a' },{ foo: 'a' },{ foo: 'a' },{ foo: 'a' },{ foo: 'a' },{ foo: 'a' },{ foo: 'a' }]
safe.arrOf.objWith(true, config1); // []
safe.arrOf.objWith(false, config1); // []
safe.arrOf.objWith(123, config1); // []
safe.arrOf.objWith('foobar', config1); // []
safe.arrOf.objWith({ foo: 'bar' }, config1); // []
safe.arrOf.objWith(null, config1); // []

const config2: ObjWithConfig<{ foo: string, bar: number }> = {
  ...config1,
  bar: {
    fallback: 78,
    safeFn: (v, f) => safe.num(v, true, 0, 100, f)
  }
};
safe.arrOf.objWith([{ foo: 1 }, { bar: 2 }], config2); // [ { foo: 'a', bar: 78 }, { bar: 2, foo: 'a' } ]
safe.arrOf.objWith(['foo', 1, true, null, undefined, [], {}], config2); // [{ foo: 'a', bar: 78 },{ foo: 'a', bar: 78 },{ foo: 'a', bar: 78 },{ foo: 'a', bar: 78 },{ foo: 'a', bar: 78 },{ foo: 'a', bar: 78 },{ foo: 'a', bar: 78 }]
safe.arrOf.objWith(true, config2); // []
safe.arrOf.objWith(false, config2); // []
safe.arrOf.objWith(123, config2); // []
safe.arrOf.objWith('foobar', config2); // []
safe.arrOf.objWith({ foo: 'bar' }, config2); // []
safe.arrOf.objWith(null, config2); // []
#Parameter NameRequiredTypeDefault
0inputYesT[]
1objConfigYesObjWithConfig<T>
2allowCompositionNobooleantrue
3fallbackArrNoT[][]
4arrMinLengthNonumber0
5arrMaxLengthNonumberInfinity
Return Type
T[]

[↑ Back to safe ↑]

arr
safe.arrOf.arr<T>(input: T[][], fallback: T[], fallbackArr: T[][], arrMinLength: number, arrMaxLength: number): T[][]

Process an array of arrays, ensuring that they are safe to use.

safe.arrOf.arr([['foo'], ['bar']]); // [ [ 'foo' ], [ 'bar' ] ]
safe.arrOf.arr(['foo', 1, true, null, undefined, [], {}]); // [ [], [], [], [], [], [], [] ]
safe.arrOf.arr(true); // []
safe.arrOf.arr(false); // []
safe.arrOf.arr(123); // []
safe.arrOf.arr('foobar'); // []
safe.arrOf.arr({foo: 'bar'}); // []
safe.arrOf.arr(null); // []
safe.arrOf.arr(undefined); // []

safe.arrOf.arr([['foo'], ['bar']], ['baz'], [['IPSUM']]); // [ [ 'foo' ], [ 'bar' ] ]
safe.arrOf.arr(['foo', 1, true, null, undefined, [], {}], ['baz'], [['IPSUM']]); // [ [ 'baz' ], [ 'baz' ], [ 'baz' ], [ 'baz' ], [ 'baz' ], [], [ 'baz' ] ]
safe.arrOf.arr(true, ['baz'], [['IPSUM']]); // [ [ 'IPSUM' ] ]
safe.arrOf.arr(false, ['baz'], [['IPSUM']]); // [ [ 'IPSUM' ] ]
safe.arrOf.arr(123, ['baz'], [['IPSUM']]); // [ [ 'IPSUM' ] ]
safe.arrOf.arr('foobar', ['baz'], [['IPSUM']]); // [ [ 'IPSUM' ] ]
safe.arrOf.arr({foo: 'bar'}, ['baz'], [['IPSUM']]); // [ [ 'IPSUM' ] ]
safe.arrOf.arr(null, ['baz'], [['IPSUM']]); // [ [ 'IPSUM' ] ]
safe.arrOf.arr(undefined, ['baz'], [['IPSUM']]); // [ [ 'IPSUM' ] ]
#Parameter NameRequiredTypeDefault
0inputYesT[][]
1fallbackNoT[]
2fallbackArrNoT[][][]
3arrMinLengthNonumber0
4arrMaxLengthNonumberInfinity
Return Type
T[][]

[↑ Back to safe ↑]

prop
safe.arrOf.prop(input: (string | number)[], fallback: string | number, fallbackArr: (string | number)[], arrMinLength: number, arrMaxLength: number): (string | number)[]

Process an array of values that can be used as properties (string or number), ensuring that they are safe to use.

safe.arrOf.prop([['foo'], ['bar']]); // [ '', '' ]
safe.arrOf.prop(['foo', 1, true, null, undefined, [], {}]); // [ 'foo', 1, 'true', '', '', '', '' ]
safe.arrOf.prop(true); // []
safe.arrOf.prop(false); // []
safe.arrOf.prop(123); // []
safe.arrOf.prop('foobar'); // []
safe.arrOf.prop({foo: 'bar'}); // []
safe.arrOf.prop(null); // []
safe.arrOf.prop(undefined); // []

safe.arrOf.prop([['foo'], ['bar']], ['baz'], ['IPSUM']); // [ [ 'baz' ], [ 'baz' ] ]
safe.arrOf.prop(['foo', 1, true, null, undefined, [], {}], ['baz'], ['IPSUM']); // [ 'foo', 1, 'true', [ 'baz' ], [ 'baz' ], [ 'baz' ],[ 'baz' ] ]
safe.arrOf.prop(true, ['baz'], ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.prop(false, ['baz'], ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.prop(123, ['baz'], ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.prop('foobar', ['baz'], ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.prop({foo: 'bar'}, ['baz'], ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.prop(null, ['baz'], ['IPSUM']); // [ 'IPSUM' ]
safe.arrOf.prop(undefined, ['baz'], ['IPSUM']); // [ 'IPSUM' ]
#Parameter NameRequiredTypeDefault
0inputYes(string | number)[]
1fallbackNostring | number
2fallbackArrNo(string | number)[][]
3arrMinLengthNonumber0
4arrMaxLengthNonumberInfinity
Return Type
(string | number)[]

[↑ Back to safe ↑]

ObjWithConfig

safe.ObjWithConfig;

A type for defining the configuration of an object when using safe.objWith.

[↑ Back to safe ↑]

ObjWithPropConfig
safe.ObjWithPropConfig;

A type for defining what is required for a property of an object when using safe.objWith.

[↑ Back to safe ↑]

Types

Some commonly used typescript types

[↑ Back to top ↑]

Partial

Partial<T>;

Makes all properties in T optional.

interface ITest {
  a: string,
  b: boolean
};
type PartialTest = Partial<ITest>; // { a?: string, b?: boolean }

[↑ Back to Types ↑]

KeysOnly

KeysOnly<T>;

Makes all the values equal to the keys of T

interface ITest {
  a: string,
  b: boolean
};
type KeysOnlyTest = KeysOnly<ITest>; // { a: 'a', b: 'b' }

[↑ Back to Types ↑]

Numbered

Numbered<T>;

Makes all the values numbers

interface ITest {
  a: string,
  b: boolean
};
type NumberedTest = Numbered<ITest>; // { a: number, b: number }

[↑ Back to Types ↑]

OfType<O, T>

OfType<O, T>;

Makes all the properties of object O have type T

Note: This is the same as RemapOf<O, T>

interface IExample {
  a: string;
  b: boolean;
}
OfType<IExample, number>; // { a: number; b: number; }

[↑ Back to Types ↑]

ObjOfType

ObjOfType<T>;

An object with any properties of type T

type Example = [number, number];
ObjOfType<Example>; // { [key: string]: Example; }

[↑ Back to Types ↑]

RemapOf<O, T>

RemapOf<O, T>;

Remap a given interface (O) with all properties of type T

Note: This is the same as OfType<O, T>

interface IExample {
  a: string;
  b: boolean;
}
RemapOf<IExample, number>; // { a: number; b: number; }

[↑ Back to Types ↑]

Notes

Over 9000 unit tests

[↑ Back to top ↑]

FAQs

Package last updated on 07 Jan 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc