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.3.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
10
decreased by-89.13%
Maintainers
1
Weekly downloads
 
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
  • waiters.wait

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

[↑ Back to top ↑]

waitUntil

  • waitUntil
  • waiters.waitUntil

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

[↑ Back to top ↑]

waitFor

  • waitFor
  • waiters.waitFor

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

[↑ Back to top ↑]

waitEvery

  • waitEvery
  • waiters.waitEvery

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

[↑ Back to top ↑]

stopInterval

  • stopInterval
  • waiters.stopInterval
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));

[↑ Back to top ↑]

interval

  • interval
  • waiters.interval

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));

[↑ Back to top ↑]

fn

A collection of useful higher-order functions.

[↑ Back to top ↑]

noop

  • fn.noop

No operation. Do nothing, return nothing.

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

[↑ Back to top ↑]

noact

  • fn.noact

No action. Returns the first argument it receives.

const items = stuff
  .map(condition ? mapSomething : fn.noact)

[↑ Back to top ↑]

result

  • fn.result

Returns a function that returns a function that returns the first argument.

const items = stuff
  .filter(condition ? mapSomething : fn.result(true))

[↑ Back to top ↑]

resolve

  • fn.resolve

Returns an async function that resolves to the first argument

Like fn.result, but wrapped in a Promise

[↑ Back to top ↑]

reject

  • fn.reject

Returns an async function that rejects with the first argument

[↑ Back to top ↑]

filters

  • fn.filters

Collection of functions that can be used with Array.filter

[↑ Back to top ↑]

exists
  • fn.exists
  • fn.filters.exists
  • filters.exists

Returns true if item isn't null or undefined.

[null, 1, undefined, 2].filter(fn.exists); // [1, 2]

[↑ Back to top ↑]

isTruthy
  • fn.isTruthy
  • fn.filters.isTruthy
  • filters.isTruthy

Returns true if item is truthy.

[0, 1, 2].filter(fn.isTruthy); // [1, 2]
['', 'a', 'b'].filter(fn.isTruthy); // ['a', 'b']

[↑ Back to top ↑]

isFalsy
  • fn.isFalsy
  • fn.filters.isFalsy
  • filters.isFalsy

Returns true if item is falsy.

[0, 1, 2].filter(fn.isFalsy); // [0]
['', 'a', 'b'].filter(fn.isFalsy); // ['']

[↑ Back to top ↑]

isEmpty
  • fn.isEmpty
  • fn.filters.isEmpty
  • filters.isEmpty

Returns true if item's length is 0

['', 'a', 'b'].filter(fn.isEmpty); // ['']
[[], [1], [2]].filter(fn.isEmpty); // [[]]

[↑ Back to top ↑]

isNotEmpty
  • fn.isNotEmpty
  • fn.filters.isNotEmpty
  • filters.isNotEmpty

Returns true if item's length is 1 or more

['', 'a', 'b'].filter(fn.isNotEmpty); // ['a', 'b']
[[], [1], [2]].filter(fn.isNotEmpty); // [[1], [2]]

[↑ Back to top ↑]

isEqual
  • fn.isEqual
  • fn.filters.isEqual
  • filters.isEqual

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

[0, 1, 2].filter(fn.isEqual(1)); // [1]

[↑ Back to top ↑]

isNotEqual
  • fn.isNotEqual
  • fn.filters.isNotEqual
  • filters.isNotEqual

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

[0, 1, 2].filter(fn.isNotEqual(1)); // [0, 2]

[↑ Back to top ↑]

dedupe
  • fn.dedupe
  • fn.filters.dedupe
  • filters.dedupe

Removes duplicate items from an array.

[0, 1, 2, 1, 0].filter(fn.dedupe); // [0, 1, 2]

[↑ Back to top ↑]

dedupeMapped
  • fn.dedupeMapped
  • fn.filters.dedupeMapped
  • filters.dedupeMapped

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 ])

[↑ Back to top ↑]

maps

  • fn.maps

Collection of functions that can be used with Array.map

[↑ Back to top ↑]

toString
  • fn.toString
  • fn.maps.toString
  • maps.toString

Maps the item to a string.

[0, 1, 2].map(fn.toString); // ['0', '1', '2']

[↑ Back to top ↑]

toNumber
  • fn.toNumber
  • fn.maps.toNumber
  • maps.toNumber

Maps the item to a number.

['0', '1', '2'].map(fn.toNumber); // [0, 1, 2]

[↑ Back to top ↑]

toBool
  • fn.toBool
  • fn.maps.toBool
  • maps.toBool

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]

[↑ Back to top ↑]

toProp
  • fn.toProp
  • fn.maps.toProp
  • maps.toProp

Maps the item to a given property of the item

[{name: 'Jack'}, {name: 'Jill'}].map(fn.toProp('name')); // ['Jack', 'Jill']

[↑ Back to top ↑]

toFixed
  • fn.toFixed
  • fn.maps.toFixed
  • maps.toFixed

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]

[↑ Back to top ↑]

sorts

  • fn.sorts

Collection of functions that can be used with Array.sort

[↑ Back to top ↑]

asc
  • fn.asc
  • fn.sorts.asc
  • sorts.asc

Sort ascending.

[2, 4, 3, 1].sort(fn.asc); // [1, 2, 3, 4]

[↑ Back to top ↑]

desc
  • fn.desc
  • fn.sorts.desc
  • sorts.desc

Sort descending.

[2, 4, 3, 1].sort(fn.asc); // [4, 3, 2, 1]

[↑ Back to top ↑]

byProp
  • fn.byProp
  • fn.sorts.byProp
  • sorts.byProp

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}]

[↑ Back to top ↑]

nearestTo
  • fn.nearestTo
  • fn.sorts.nearestTo
  • sorts.nearestTo

Sort by the nearest value to the given value.

const people = [2, 4, 3, 1];
people.sort(fn.nearestTo(3)); // [3, 2, 4, 1]

[↑ Back to top ↑]

furthestFrom
  • fn.furthestFrom
  • fn.sorts.furthestFrom
  • sorts.furthestFrom

Sort by the furthest value to the given value.

const people = [2, 4, 3, 1];
people.sort(fn.furthestFrom(3)); // [1, 2, 4, 3]

[↑ Back to top ↑]

arrayAsc
  • fn.arrayAsc
  • fn.sorts.arrayAsc
  • sorts.arrayAsc

Sort an array of arrays in ascending order

[↑ Back to top ↑]

arrayDesc
  • fn.arrayDesc
  • fn.sorts.arrayDesc
  • sorts.arrayDesc

Sort an array of arrays in descending order

[↑ Back to top ↑]

reduces

  • fn.reduces

Collection of functions that can be used with Array.reduce

[↑ Back to top ↑]

combine
  • fn.combine
  • fn.reduces.combine
  • reduces.combine

Adds or concats the items

[1, 2, 3].reduce(fn.combine); // 6
['a', 'b', 'c'].reduce(fn.combine); // 'abc'

[↑ Back to top ↑]

combineProp
  • fn.combineProp
  • fn.reduces.combineProp
  • reduces.combineProp

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'

[↑ Back to top ↑]

mode
  • fn.mode
  • fn.reduces.mode
  • reduces.mode

Returns the most common value in an array.

[1, 2, 3, 2, 1, 1].reduce(fn.mode); // 1

[↑ Back to top ↑]

modeMapped
  • fn.modeMapped
  • fn.reduces.modeMapped
  • reduces.modeMapped

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 ])

[↑ Back to top ↑]

everys

  • fn.everys

Collection of functions that can be used with Array.every

[↑ Back to top ↑]

isAllEqual
  • fn.isAllEqual
  • fn.everys.isAllEqual
  • everys.isAllEqual

Returns if all the items are equal to one another.

[1, 1, 1].every(fn.isAllEqual); // true
[1, 2, 1].every(fn.isAllEqual); // false

[↑ Back to top ↑]

ArrayTools

  • ArrayTools

A collection of useful array functions.

[↑ Back to top ↑]

range

  • range
  • ArrayTools.range

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]

[↑ Back to top ↑]

zip

  • zip
  • ArrayTools.zip

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'] ]

[↑ Back to top ↑]

zipMax

  • zipMax
  • ArrayTools.zipMax

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 ] ]

[↑ Back to top ↑]

sortByMapped

  • sortByMapped
  • ArrayTools.sortByMapped

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']

[↑ Back to top ↑]

randomise

  • randomise
  • ArrayTools.randomise

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 ]

[↑ Back to top ↑]

reverse

  • reverse
  • ArrayTools.reverse

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]

[↑ Back to top ↑]

entries

  • entries
  • ArrayTools.entries

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'
}

[↑ Back to top ↑]

repeat

  • repeat
  • ArrayTools.repeat

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' ]

[↑ Back to top ↑]

roll

  • roll
  • ArrayTools.roll

'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 ]

[↑ Back to top ↑]

sortNumberedText

  • sortNumberedText
  • ArrayTools.sortNumberedText

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' ]

[↑ Back to top ↑]

partition

  • partition
  • ArrayTools.partition

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 ] ]

[↑ Back to top ↑]

groupObj

  • groupObj
  • ArrayTools.groupObj

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.id); // {
//   1: [ { group: 1, name: 'a' }, { group: 1, name: 'c' } ],
//   2: [ { group: 2, name: 'b' } ]
// }

[↑ Back to top ↑]

group

  • group
  • ArrayTools.group

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.groupObj(arr, item => item.id); // [
//   [ { group: 1, name: 'a' }, { group: 1, name: 'c' } ],
//   [ { group: 2, name: 'b' } ]
// ]

[↑ Back to top ↑]

utils

  • ArrayTools.utils

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

[↑ Back to top ↑]

isNumString
  • ArrayTools.utils.isNumString

Returns true if the given string is a number

[↑ Back to top ↑]

partitionNums
  • ArrayTools.utils.partitionNums

Splits a string into an array of strings and numbers

[↑ Back to top ↑]

ObjectTools

A collection of functions for working with objects

[↑ Back to top ↑]

remodel

  • ObjectTools.remodel

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 }

[↑ Back to top ↑]

remodelEach

  • ObjectTools.remodelEach

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 }

[↑ Back to top ↑]

map

  • ObjectTools.map

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'}

[↑ Back to top ↑]

mapValues

  • ObjectTools.mapValues

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'}

[↑ Back to top ↑]

mapKeys

  • ObjectTools.mapKeys

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}

[↑ Back to top ↑]

filter

  • ObjectTools.filter

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 }

[↑ Back to top ↑]

clean

  • ObjectTools.clean

Removes properties with undefined values

ObjectTools.clean({a: 1, b: undefined, c: 3}) // { a: 1, c: 3 }

[↑ Back to top ↑]

StringTools

A collection of string utilities

[↑ Back to top ↑]

capitalise

  • StringTools.capitalise

Capitalises the first letter of each word in a string

StringTools.capitalise('hello world'); // 'Hello World'

[↑ Back to top ↑]

angloise

  • StringTools.angloise

Remove accents from a string

StringTools.angloise('éèêë'); // 'eeee'

[↑ Back to top ↑]

clean

  • StringTools.clean

Remove accents and non alphanumerics from a string

StringTools.clean('éèêë_--ab0'); // 'eeeeab0'

[↑ Back to top ↑]

StringCaseHandler

toLowerCamelCase
  • StringTools.toLowerCamelCase
  • StringTools.fromSlugCase.toLowerCamelCase
  • StringTools.fromSnakeCase.toLowerCamelCase
  • StringTools.fromSpaced.toLowerCamelCase
  • StringTools.fromCamelCase.toLowerCamelCase

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

[↑ Back to top ↑]

toUpperCamelCase
  • StringTools.toUpperCamelCase
  • StringTools.fromSlugCase.toUpperCamelCase
  • StringTools.fromSnakeCase.toUpperCamelCase
  • StringTools.fromSpaced.toUpperCamelCase
  • StringTools.fromCamelCase.toUpperCamelCase

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

[↑ Back to top ↑]

toCamelCase
  • StringTools.toCamelCase
  • StringTools.fromSlugCase.toCamelCase
  • StringTools.fromSnakeCase.toCamelCase
  • StringTools.fromSpaced.toCamelCase
  • StringTools.fromCamelCase.toCamelCase

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

[↑ Back to top ↑]

toLowerSlugCase
  • StringTools.toLowerSlugCase
  • StringTools.fromSlugCase.toLowerSlugCase
  • StringTools.fromSnakeCase.toLowerSlugCase
  • StringTools.fromSpaced.toLowerSlugCase
  • StringTools.fromCamelCase.toLowerSlugCase

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

[↑ Back to top ↑]

toUpperSlugCase
  • StringTools.toUpperSlugCase
  • StringTools.fromSlugCase.toUpperSlugCase
  • StringTools.fromSnakeCase.toUpperSlugCase
  • StringTools.fromSpaced.toUpperSlugCase
  • StringTools.fromCamelCase.toUpperSlugCase

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

[↑ Back to top ↑]

toSlugCase
  • StringTools.toSlugCase
  • StringTools.fromSlugCase.toSlugCase
  • StringTools.fromSnakeCase.toSlugCase
  • StringTools.fromSpaced.toSlugCase
  • StringTools.fromCamelCase.toSlugCase

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

[↑ Back to top ↑]

toLowerSnakeCase
  • StringTools.toLowerSnakeCase
  • StringTools.fromSlugCase.toLowerSnakeCase
  • StringTools.fromSnakeCase.toLowerSnakeCase
  • StringTools.fromSpaced.toLowerSnakeCase
  • StringTools.fromCamelCase.toLowerSnakeCase

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

[↑ Back to top ↑]

toUpperSnakeCase
  • StringTools.toUpperSnakeCase
  • StringTools.fromSlugCase.toUpperSnakeCase
  • StringTools.fromSnakeCase.toUpperSnakeCase
  • StringTools.fromSpaced.toUpperSnakeCase
  • StringTools.fromCamelCase.toUpperSnakeCase

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

[↑ Back to top ↑]

toSnakeCase
  • StringTools.toSnakeCase
  • StringTools.fromSlugCase.toSnakeCase
  • StringTools.fromSnakeCase.toSnakeCase
  • StringTools.fromSpaced.toSnakeCase
  • StringTools.fromCamelCase.toSnakeCase

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

[↑ Back to top ↑]

toLowerSpaced
  • StringTools.toLowerSpaced
  • StringTools.fromSlugCase.toLowerSpaced
  • StringTools.fromSnakeCase.toLowerSpaced
  • StringTools.fromSpaced.toLowerSpaced
  • StringTools.fromCamelCase.toLowerSpaced

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

[↑ Back to top ↑]

toUpperSpaced
  • StringTools.toUpperSpaced
  • StringTools.fromSlugCase.toUpperSpaced
  • StringTools.fromSnakeCase.toUpperSpaced
  • StringTools.fromSpaced.toUpperSpaced
  • StringTools.fromCamelCase.toUpperSpaced

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

[↑ Back to top ↑]

toCapitalisedSpaced
  • StringTools.toCapitalisedSpaced
  • StringTools.fromSlugCase.toCapitalisedSpaced
  • StringTools.fromSnakeCase.toCapitalisedSpaced
  • StringTools.fromSpaced.toCapitalisedSpaced
  • StringTools.fromCamelCase.toCapitalisedSpaced

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

[↑ Back to top ↑]

toSpaced
  • StringTools.toSpaced
  • StringTools.fromSlugCase.toSpaced
  • StringTools.fromSnakeCase.toSpaced
  • StringTools.fromSpaced.toSpaced
  • StringTools.fromCamelCase.toSpaced

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

[↑ Back to top ↑]

toCharacterSeparated
  • StringTools.toCharacterSeparated
  • StringTools.fromSlugCase.toCharacterSeparated
  • StringTools.fromSnakeCase.toCharacterSeparated
  • StringTools.fromSpaced.toCharacterSeparated
  • StringTools.fromCamelCase.toCharacterSeparated

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

[↑ Back to top ↑]

fromSlugCase

Has the following methods:

  • 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

[↑ Back to top ↑]

fromSnakeCase

Has the following methods:

  • 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

[↑ Back to top ↑]

fromSpaced

Has the following methods:

  • 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

[↑ Back to top ↑]

fromCamelCase

Has the following methods:

  • 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

[↑ Back to top ↑]

clx

  • clx
  • StringTools.clx

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'

[↑ Back to top ↑]

MathsTools

A collection of mathematical functions.

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

[↑ Back to top ↑]

fixFloat

  • ff
  • MathsTools.ff
  • MathsTools.fixFloat

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

[↑ Back to top ↑]

addAll

  • MathsTools.addAll

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

[↑ Back to top ↑]

round

floorTo
  • MathsTools.floorTo
  • MathsTools.round.floorTo

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

[↑ Back to top ↑]

roundTo
  • MathsTools.round.to
  • MathsTools.roundTo
  • MathsTools.round.roundTo

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

[↑ Back to top ↑]

ceilTo
  • MathsTools.ceilTo
  • MathsTools.round.ceilTo

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

[↑ Back to top ↑]

lerp

  • MathsTools.lerp

Linearly interpolates between two values.

MathsTools.lerp(0.5, 0, 10); // 5

[↑ Back to top ↑]

lerpArray

  • MathsTools.lerpArray

Linearly interpolates between the values of 2 arrays.

MathsTools.lerpArray(0.5, [0, 0, 0], [10, 100, 1000]) // [5, 50, 500]

[↑ Back to top ↑]

lerpObj

  • MathsTools.lerpObj

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}

[↑ Back to top ↑]

clamp

  • MathsTools.clamp

Clamps a value between a min and max.

MathsTools.clamp(5, 0, 10); // 5
MathsTools.clamp(-5, 0, 10); // 0

[↑ Back to top ↑]

getOrdinal

  • MathsTools.getOrdinal

Gets the ordinal suffix for a number.

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'

[↑ Back to top ↑]

PromiseTools

A collection of promise utilities

[↑ Back to top ↑]

getDeferred

  • getDeferred
  • PromiseTools.getDeferred

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();

[↑ Back to top ↑]

all

  • all
  • PromiseTools.all

An alias for Promise.all

[↑ Back to top ↑]

allLimit

  • allLimit
  • PromiseTools.allLimit

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

[↑ Back to top ↑]

each

  • each
  • PromiseTools.each

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

[↑ Back to top ↑]

eachLimit

  • eachLimit
  • PromiseTools.eachLimit

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

[↑ Back to top ↑]

map

  • map
  • PromiseTools.map

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)

[↑ Back to top ↑]

mapLimit

  • mapLimit
  • PromiseTools.mapLimit

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)

[↑ Back to top ↑]

allObj

  • allObj
  • PromiseTools.allObj

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

[↑ Back to top ↑]

allLimitObj

  • allLimitObj
  • PromiseTools.allLimitObj

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

[↑ Back to top ↑]

DeferredPromise

  • DeferredPromise
  • PromiseTools.DeferredPromise

A deferred promise

[↑ Back to top ↑]

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 top ↑]

HSLValues

  • ColourTools.HSLValues

A type with 3 numbers:

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

[↑ Back to top ↑]

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 top ↑]

parse

  • ColourTools.parse

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]

[↑ Back to top ↑]

toHex

  • ColourTools.toHex

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

ColourTools.toHex([255, 0, 0]) // '#FF0000'

[↑ Back to top ↑]

getLuminance

  • ColourTools.getLuminance

IMPORTANT: This is not the same as the HSL luminance 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

[↑ Back to top ↑]

toYUV

  • ColourTools.toYUV

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]

[↑ Back to top ↑]

toHSL

  • ColourTools.toHSL

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]

[↑ Back to top ↑]

fromHSL

  • ColourTools.fromHSL

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]

[↑ Back to top ↑]

invertColour

  • ColourTools.invertColour

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 ]

[↑ Back to top ↑]

getContrastedColour

  • ColourTools.getContrastedColour

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]

[↑ Back to top ↑]

getLimitedColour

  • ColourTools.getLimitedColour

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 ]

[↑ Back to top ↑]

TimeTools

A collection of time-related utility functions.

[↑ Back to top ↑]

toReadableDuration

  • TimeTools.toReadableDuration

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'

[↑ Back to top ↑]

ErrorTools

Functions for handling errors.

[↑ Back to top ↑]

tryOr

  • tryOr
  • ErrorTools.tryOr

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());

[↑ Back to top ↑]

retry

  • retry
  • ErrorTools.retry

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());

[↑ Back to top ↑]

retryOr

  • retryOr
  • ErrorTools.retryOr

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), true, () => getSomething());

[↑ Back to top ↑]

progressBar

A progress bar that can be used in the terminal.

NOTE: This is eventually be moved to swiss-node

[↑ Back to top ↑]

printLn

  • printLn
  • progressBar.printLn

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

[↑ Back to top ↑]

Options

  • ProgressBarOptions
  • progressBar.ProgressBarOptions

All options are optional.

PropertyDefaultDescription
prefix''String to show to left of progress bar
prefixWidth1Min width of prefix - 10 => Example˽˽˽
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
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
showCurrent'▏'Show the 'current' segment of the bar seperately
currentChar'▏'Character to use the the 'current' segment

[↑ Back to top ↑]

getProgressBar

  • getProgressBar
  • progressBar.getProgressBar

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]

[↑ Back to top ↑]

update
  • getProgressBar().update

Trigger the progress bar to update/rerender

[↑ Back to top ↑]

next
  • getProgressBar().next

Set the progress bar to the next value

[↑ Back to top ↑]

set
  • getProgressBar().set

Set the progress bar to a specific value

[↑ Back to top ↑]

reset
  • getProgressBar().reset

Set the progress bar to 0

[↑ Back to top ↑]

start
  • getProgressBar().start

Start displaying the progress bar

[↑ Back to top ↑]

finish
  • getProgressBar().finish

Stop displaying the progress bar

[↑ Back to top ↑]

max
  • getProgressBar().max

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

[↑ Back to top ↑]

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~
CHEV_LFTsymbols.CHEV_LFT
CHEV_RGTsymbols.CHEV_RGT
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

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) // '¹²³⁴⁵⁶⁷⁸⁹⁰'

[↑ Back to top ↑]

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 top ↑]

setDefaultPauseTime
  • queue.setDefaultPauseTime
  • new QueueManager().setDefaultPauseTime

Sets the default pause time for pauses between queue items.

[↑ Back to top ↑]

setPauseTime
  • queue.setPauseTime
  • new QueueManager().setPauseTime

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

[↑ Back to top ↑]

add
  • queue.add
  • new QueueManager().add

Adds a function to the queue.

[↑ Back to top ↑]

new
  • queue.new
  • new QueueManager().new

Creates a new QueueManager instance.

[↑ Back to top ↑]

queue

  • queue

An instance of QueueManager

See QueueManager for more information.

[↑ Back to top ↑]

timer

A debug tool for measuring the duration of code blocks.

[↑ Back to top ↑]

getTimer

  • getTimer

Usage:

const timer = getTimer('Example', false, chalk.red, chalk, {
  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

[↑ Back to top ↑]

timer

  • timer

Global timer

[↑ Back to top ↑]

Helper Types

Some commonly used types

[↑ Back to top ↑]

Partial

  • Partial

Makes all properties in T optional.

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

[↑ Back to top ↑]

KeysOnly

  • KeysOnly

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 top ↑]

Numbered

  • Numbered

Makes all the values numbers

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

[↑ Back to top ↑]

OfType<T, U>

  • OfType

Makes all the properties of object T have type U

[↑ Back to top ↑]

ObjOfType

  • ObjOfType

An object with any properties of type T

[↑ Back to top ↑]

RemapOf<O, T>

  • RemapOf

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

[↑ Back to top ↑]

Notes

These are used in non-vital personal projects and scripts.

Need to be better tested before being used in prod.

Failing/erroring/rejected promises may not behave as expected.

[↑ Back to top ↑]

FAQs

Package last updated on 04 Jul 2023

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