Skip to main content

@olmokit/utils

Interfaces​

Other​

AnyAsyncFunction​

Ƭ AnyAsyncFunction: (...args: any[]) => Promise<any>

Type declaration​

▸ (...args): Promise<any>

Parameters​
NameType
...argsany[]
Returns​

Promise<any>

Defined in​

getType.ts:12


AnyClass​

Ƭ AnyClass: (...args: any[]) => any

Type declaration​

• (...args)

Parameters​
NameType
...argsany[]

Defined in​

getType.ts:13


AnyFunction​

Ƭ AnyFunction: (...args: any[]) => any

Type declaration​

▸ (...args): any

Parameters​
NameType
...argsany[]
Returns​

any

File

Same as is-what plus:

  • isFormData
  • isInt
  • isFloat

Defined in​

getType.ts:11


AnythingFalsy​

Ƭ AnythingFalsy: null | undefined | 0 | ""

Whatever that in javascript returns false when checked in an if condition

Defined in​

types.ts:7


ClsxClassValue​

Ƭ ClsxClassValue: ClassValue

Defined in​

clsx.ts:13


DebounceOptions​

Ƭ DebounceOptions<Result>: Object

Categroy

functionn

Type parameters​

Name
Result

Type declaration​

NameType
callback?(data: Result) => void
isImmediate?boolean
maxWait?number

Defined in​

debouncePromise.ts:25


KeysStartsWith​

Ƭ KeysStartsWith<T, S>: keyof PickStartsWith<T, S>

Returns a union of all the keys of an object T which starts with S.

Type parameters​

NameType
Textends object
Sextends string

Defined in​

types.ts:20


KeysTailsStartsWith​

Ƭ KeysTailsStartsWith<T, S>: keyof PickStartsWithTails<T, S>

Returns a union of all the keys of an object T which starts with S. The strings in the produced union have S removed.

Type parameters​

NameType
Textends object
Sextends string

Defined in​

types.ts:37


PickStartsWith​

Ƭ PickStartsWith<T, S>: { [K in keyof T as K extends `${S}${string}` ? K : never]: T[K] }

Pick the keys of an object T that starts with S. It produces a mapped type with a subset of T whose keys start with S.

Type parameters​

NameType
Textends object
Sextends string

Defined in​

types.ts:13


PickStartsWithTails​

Ƭ PickStartsWithTails<T, S>: { [K in keyof T as K extends `${S}${string}` ? Replace<K, S, ""> : never]: T[K] }

Pick the keys of an object T that starts with S. It produces a mapped type with a subset of T whose keys start with S and have S removed.

Type parameters​

NameType
Textends object
Sextends string

Defined in​

types.ts:29


PlainObject​

Ƭ PlainObject: Record<string | number | symbol, any>

Defined in​

getType.ts:14


TypeGuard​

Ƭ TypeGuard<A, B>: (payload: A) => payload is B

Type parameters​

NameType
AA
Bextends A

Type declaration​

▸ (payload): payload is B

Parameters​
NameType
payloadA
Returns​

payload is B

Defined in​

getType.ts:16


getType​

▸ getType(payload): string

Returns the object type of the given payload

Parameters​

NameType
payloadany

Returns​

string

Defined in​

getType.ts:21


matchSorter​

▸ matchSorter<ItemType>(items, value, options?): ItemType[]

Takes an array of items and a value and returns a new array with the items that match the given value

Type parameters​

NameType
ItemTypestring

Parameters​

NameTypeDescription
itemsreadonly ItemType[]the items to sort
valuestringthe value to use for ranking
optionsMatchSorterOptions<ItemType>Some options to configure the sorter

Returns​

ItemType[]

  • the new sorted array

Defined in​

matchSorter.ts:101

array​

addOrReplaceAtIdx​

▸ addOrReplaceAtIdx<T>(list, newItem, newIdx?): T[]

Add or replace an item in the given array, it returns a new array (immutable). Typescript wise this is meant to keep the same type on the newly returned array, therefore the newItem must match the type of the list items.

Type parameters​

Name
T

Parameters​

NameType
listT[]
newItemT
newIdx?number

Returns​

T[]

Defined in​

addOrReplaceAtIdx.ts:8


arrayOfAll​

▸ arrayOfAll<T>(): <U>(array: U & [T] extends [U[number]] ? unknown : "Invalid") => U & [T] extends [U[number]] ? unknown : "Invalid"

Ensure an array contains all desired values

Type parameters​

Name
T

Returns​

fn

▸ <U>(array): U & [T] extends [U[number]] ? unknown : "Invalid"

Type parameters​
NameType
Uextends T[]
Parameters​
NameType
arrayU & [T] extends [U[number]] ? unknown : "Invalid"
Returns​

U & [T] extends [U[number]] ? unknown : "Invalid"

Borrows

SO comment by CertainPerformance

Usage

type Fruit = "pear" | "apple" | "orange";

const arrayOfAllFruits = arrayOfAll<Fruit>();

const allFruits = arrayOfAllFruits([
"pear",
"apple",
"orange"
]); // ts compiler ok

const allFruits = arrayOfAllFruits([
"pear",
"apple",
]); // ts compiler fails

Defined in​

arrayOfAll.ts:27


arraySum​

▸ arraySum(numbers): number

Sum array of numbers

Parameters​

NameType
numbersnumber[]

Returns​

number

Defined in​

arraySum.ts:7


arrayToLookup​

▸ arrayToLookup<T>(array?): Record<T, 1>

Maps a simple flat array to a lookup dictionary object

Type parameters​

NameType
Textends string | number | symbol

Parameters​

NameType
arrayT[]

Returns​

Record<T, 1>

Defined in​

arrayToLookup.ts:6


chunkByChunks​

▸ chunkByChunks<T>(arr, nrOfChunks, balanced?): T[][]

Type parameters​

Name
T

Parameters​

NameType
arrT[]
nrOfChunksnumber
balanced?boolean

Returns​

T[][]

See

https://stackoverflow.com/a/8189268/1938970 TODO: untested

Defined in​

chunkByChunks.ts:6


chunkBySize​

▸ chunkBySize<T>(arr, size): T[][]

Type parameters​

Name
T

Parameters​

NameType
arrT[]
sizenumber

Returns​

T[][]

See

https://stackoverflow.com/a/40682136/1938970

Defined in​

chunkBySize.ts:5


findDuplicatedIndexes​

▸ findDuplicatedIndexes(arr): Record<number, true>

Parameters​

NameType
arrany[]

Returns​

Record<number, true>

Defined in​

findDuplicatedIndexes.ts:4


getEmptyArray​

▸ getEmptyArray(length): undefined[]

Returns an array of undefined values of the desired length, useful to build skeleton UIs.

Parameters​

NameType
lengthstring | number

Returns​

undefined[]

Defined in​

getEmptyArray.ts:9


mapListBy​

▸ mapListBy<T>(array?, key?): Record<T[keyof T], T>

Maps an array of objects into a map keyed with the given key

Type parameters​

NameType
Textends Record<string | number | symbol, any>

Parameters​

NameType
arrayT[]
keykeyof T

Returns​

Record<T[keyof T], T>

Defined in​

mapListBy.ts:6


moveSortableArrayItemByKey​

▸ moveSortableArrayItemByKey<T, K>(items, key, fromItem, toItem): T[]

Move item from one place to another in a sortable array of objects, re-ordering the array accrodingly (no swapping of position). This is useful for drag and drop functionalities

Type parameters​

NameType
TT
Kextends string | number | symbol

Parameters​

NameType
itemsT[]
keyK
fromItemPick<T, K>
toItemPick<T, K>

Returns​

T[]

Defined in​

moveSortableArrayItemByKey.ts:8


removeDuplicatesByKey​

▸ removeDuplicatesByKey<T>(array?, key): T[]

Remove duplicated array objects, equality is determined by a strict (===) comparison of each object's given key

Type parameters​

NameType
Textends Record<string | number | symbol, any>

Parameters​

NameType
arrayT[]
keykeyof T

Returns​

T[]

Defined in​

removeDuplicatesByKey.ts:7


removeDuplicatesComparing​

▸ removeDuplicatesComparing<T>(from, to): T[]

Type parameters​

Name
T

Parameters​

NameType
fromany[]
toT[]

Returns​

T[]

Defined in​

removeDuplicatesComparing.ts:7


removeIndexesFromArray​

▸ removeIndexesFromArray<T>(arr, indexes): T[]

Type parameters​

Name
T

Parameters​

NameType
arrT[]
indexesRecord<number, true>

Returns​

T[]

Defined in​

removeIndexesFromArray.ts:4


shuffle​

▸ shuffle<T>(array): T[]

Creates an array of shuffled values, using a version of the Fisher-Yates shuffle.

Type parameters​

Name
T

Parameters​

NameTypeDescription
arrayT[]The array to shuffle.

Returns​

T[]

The new shuffled array.

Borrows

lodash.shuffle

Example

shuffle([1, 2, 3, 4])
// => [4, 1, 3, 2]

Defined in​

shuffle.ts:16

async​

Deferred​

Ƭ Deferred<T>: Promise<T> & { reject: PromiseConstructor["reject"] ; resolve: PromiseConstructor["resolve"] }

Type parameters​

Name
T

Defined in​

Defer.ts:4


Defer​

▸ Defer<T>(): Deferred<T>

Type parameters​

Name
T

Returns​

Deferred<T>

See

https://stackoverflow.com/a/37673534/1938970

Example

const deferred = Defer();
deferred.resolve();
deferred.then(handleSuccess, handleError);

Defined in​

Defer.ts:23


tryUntil​

▸ tryUntil(test, timeout, interval, resolve, reject?): void

Parameters​

NameTypeDescription
test() => boolean-
timeoutnumberin ms
intervalnumberin ms
resolve() => void-
reject?() => void-

Returns​

void

Borrows

Javascript: Wait Until Something Happens or Timeout

Defined in​

tryUntil.ts:10


wait​

▸ wait(milliseconds): Promise<unknown>

A promisified setTimeout

Parameters​

NameType
millisecondsnumber

Returns​

Promise<unknown>

Defined in​

wait.ts:6

cast​

ensureInt​

▸ ensureInt(input): number

Ensure input to be an integer

Parameters​

NameType
inputstring | number

Returns​

number

Defined in​

ensureInt.ts:6


errorToString​

▸ errorToString(e): string

Ensure to transform a JavaScript Error into a string (uses its message)

Parameters​

NameType
eunknown

Returns​

string

Defined in​

errorToString.ts:9


toNumber​

▸ toNumber(input?, fallback?): number

Parameters​

NameType
input?string | number
fallback?number

Returns​

number

Defined in​

toNumber.ts:6

colors​

createPalette​

▸ createPalette<TName, TShades, TColor, TMap>(name, shades): readonly [TMap, Record<`${TName}-${TShades[number][0]}`, string>, TColor[]]

Create palette, this is primarily thought to improve the reuse of a palette definition between TailwindCSS and straight ES imports

Type parameters​

NameType
TNameextends string
TShadesextends PaletteShades
TColorTShades[number][``1``]
TMapPaletteMap<TShades>

Parameters​

NameType
nameTName
shadesTShades

Returns​

readonly [TMap, Record<`${TName}-${TShades[number][0]}`, string>, TColor[]]

An array with: 1) A flat palette map 2) A TailwindCSS ready palette object 3) A flat array of colors (no special sorting, same order as the shades given as argument)

Defined in​

createPalette.ts:25


toRgba​

▸ toRgba(hex, alpha?): string

Parameters​

NameTypeDefault value
hexstringundefined
alphanumber1

Returns​

string

Defined in​

toRgba.ts:11

CookieAttributesClient​

Ƭ CookieAttributesClient: CookieAttributes

Defined in​

cookie.ts:72


CookieAttributesServer​

Ƭ CookieAttributesServer: CookieAttributes & { decode?: (input: string) => string ; encode?: (input: string) => string ; httpOnly?: boolean ; maxAge?: number }

Defined in​

cookie.ts:62


parseCookie​

▸ parseCookie<T>(str, attributes?): T

Parse a cookie header.

Parse the given cookie header string into an object The object has the various cookies as keys(names) => values

Type parameters​

NameType
Textends Record<string, unknown> = Record<string, string>

Parameters​

NameType
strstring
attributesCookieAttributesServer

Returns​

T

Defined in​

parseCookie.ts:22


readCookie​

▸ readCookie<T>(name?): T

Read cookie

Type parameters​

NameType
Textends Record<string, unknown> = Record<string, string>

Parameters​

NameType
name?null

Returns​

T

Defined in​

readCookie.ts:13

▸ readCookie<T, N>(name): T[N]

Type parameters​

NameType
Textends Record<string, unknown> = Record<string, string>
Nextends string | number | symbol = keyof T

Parameters​

NameType
nameN

Returns​

T[N]

Defined in​

readCookie.ts:16


removeCookie​

▸ removeCookie(name, attributes?): void

Parameters​

NameType
namestring
attributesCookieAttributes

Returns​

void

Defined in​

removeCookie.ts:7


serializeCookie​

▸ serializeCookie(name, val, attributes?): string

Serialize data into a cookie header.

Serialize the a name value pair into a cookie string suitable for http headers. An optional attributes object specified cookie parameters.

serialize('foo', 'bar', { httpOnly: true }) => "foo=bar; httpOnly"

Parameters​

NameType
namestring
valstring
attributesCookieAttributesServer

Returns​

string

Defined in​

serializeCookie.ts:34


setCookie​

▸ setCookie<T>(name, value, attributes?): string | undefined

Type parameters​

NameType
Textends string = string

Parameters​

NameType
namestring
valuestring | T
attributesCookieAttributes

Returns​

string | undefined

Defined in​

setCookie.ts:15

error​

errorToString​

▸ errorToString(e): string

Ensure to transform a JavaScript Error into a string (uses its message)

Parameters​

NameType
eunknown

Returns​

string

Defined in​

errorToString.ts:9

format​

gbToBytes​

▸ gbToBytes(bytes): number

Gigabytes to bytes

Parameters​

NameType
bytesnumber

Returns​

number

Defined in​

gbToBytes.ts:6


kbToBytes​

▸ kbToBytes(bytes): number

Kilobytes to bytes

Parameters​

NameType
bytesnumber

Returns​

number

Defined in​

kbToBytes.ts:6


mbToBytes​

▸ mbToBytes(bytes): number

Megabytes to bytes

Parameters​

NameType
bytesnumber

Returns​

number

Defined in​

mbToBytes.ts:6

function​

debounce​

▸ debounce<T>(fn, wait?, immediate?): (this: unknown, ...args: Parameters<T>) => void

Debounce function (with setTimeout)

Type parameters​

NameType
Textends (...args: any[]) => any

Parameters​

NameType
fnT
wait?number
immediate?boolean

Returns​

fn

▸ (this, ...args): void

Parameters​
NameType
thisunknown
...argsParameters<T>
Returns​

void

Borrows

davidwalsh/debounce

Defined in​

debounce.ts:7


debouncePromise​

▸ debouncePromise<Args, F>(func, waitMilliseconds?, options?): DebouncedFunction<Args, F>

Debounce function (with Promise)

Type parameters​

NameType
Argsextends any[]
Fextends (...args: Args) => any

Parameters​

NameTypeDefault value
funcFundefined
waitMillisecondsnumber50
optionsDebounceOptions<ReturnType<F>>{}

Returns​

DebouncedFunction<Args, F>

Borrows

chodorowicz/ts-debounce

License

MIT: Jakub Chodorowicz

Defined in​

debouncePromise.ts:57


debounceRaf​

▸ debounceRaf<T>(this, fn): (this: unknown, ...args: Parameters<T>) => void

Debounce function (with requestAnimationFrame)

Type parameters​

NameType
Textends (...args: any[]) => any

Parameters​

NameType
thisunknown
fnT

Returns​

fn

▸ (this, ...args): void

Parameters​
NameType
thisunknown
...argsParameters<T>
Returns​

void

Borrows

vanillajstoolkit/debounce

License

(c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com

Defined in​

debounceRaf.ts:8


throttle​

▸ throttle<TFn, TContext>(fn, limit, context?): (this: TContext, ...args: any[]) => undefined | Timeout

Throttle function (e.g. for resize / scroll handlers)

Type parameters​

NameType
TFnextends Function
TContextTContext

Parameters​

NameType
fnTFn
limitnumber
context?TContext

Returns​

fn

▸ (this, ...args): undefined | Timeout

Parameters​
NameType
thisTContext
...argsany[]
Returns​

undefined | Timeout

Borrows

Mobius1/Rangeable

Defined in​

throttle.ts:7


tryUntil​

▸ tryUntil(test, timeout, interval, resolve, reject?): void

Parameters​

NameTypeDescription
test() => boolean-
timeoutnumberin ms
intervalnumberin ms
resolve() => void-
reject?() => void-

Returns​

void

Borrows

Javascript: Wait Until Something Happens or Timeout

Defined in​

tryUntil.ts:10

img​

imgEmptyPixel​

• Const imgEmptyPixel: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="

Empty img pixel as a string to inline

Defined in​

imgEmptyPixel.ts:6

impl​

Emitter​

▸ Emitter<EventMap>(namespace): Object

Emitter super simple class

Events will be prefixed with the given namespace plus a . so: {namespace}.myevent

Adapted from https://github.com/developit/mitt

Regarding typescript support see:

Type parameters​

NameType
EventMapextends Object

Parameters​

NameType
namespacestring

Returns​

Object

NameType
emit<EventName>(name: EventName, data?: EventMap[EventName]) => void
on<EventName>(name: EventName, handler: (data?: EventMap[EventName]) => any) => void

Defined in​

Emitter.ts:15


clsx​

▸ clsx(...args): string

Class names utility

Parameters​

NameType
...argsClassValue[]

Returns​

string

Borrows

lukeed/clsx

License

MIT Luke Edwards https://github.com/lukeed/clsx/blob/master/license

Defined in​

clsx.ts:55


quaranteneProps​

▸ quaranteneProps<TProps, TSupectPropsKeys>(props, propsKeysToQuarantene): Omit<TProps, TSupectPropsKeys[number]> & { _: Pick<TProps, TSupectPropsKeys[number]> }

Type parameters​

NameType
TPropsextends Record<never, never>
TSupectPropsKeysextends QuaranteneProps<TProps>

Parameters​

NameType
propsTProps
propsKeysToQuaranteneTSupectPropsKeys

Returns​

Omit<TProps, TSupectPropsKeys[number]> & { _: Pick<TProps, TSupectPropsKeys[number]> }

Example

const { _: { onKeyDown }, myOwnProp, ...rest } = quaranteneProps([
"onPointerLeave",
"onPointerMove",
"onClick",
"onPointerDown",
"onPointerUp",
"onKeyDown",
]);

Defined in​

quaranteneProps.ts:16

is​

isBrowser​

• Const isBrowser: boolean

Defined in​

isBrowser.ts:5


isServer​

• Const isServer: boolean = !isBrowser

Defined in​

isServer.ts:7


isAnyObject​

▸ isAnyObject(payload): payload is PlainObject

Returns whether the payload is an any kind of object (including special classes or objects with different prototypes)

Parameters​

NameType
payloadany

Returns​

payload is PlainObject

Defined in​

isAnyObject.ts:8


isArray​

▸ isArray(payload): payload is any[]

Returns whether the payload is an array

Parameters​

NameType
payloadany

Returns​

payload is any[]

Defined in​

isArray.ts:8


isBlob​

▸ isBlob(payload): payload is Blob

Returns whether the payload is a Blob

Parameters​

NameType
payloadany

Returns​

payload is Blob

Defined in​

isBlob.ts:8


isBoolean​

▸ isBoolean(payload): payload is boolean

Returns whether the payload is a boolean

Parameters​

NameType
payloadany

Returns​

payload is boolean

Defined in​

isBoolean.ts:8


isBrowserNow​

▸ isBrowserNow(): boolean

Returns​

boolean

Defined in​

isBrowserNow.ts:7


isDate​

▸ isDate(payload): payload is Date

Returns whether the payload is a Date, and that the date is valid

Parameters​

NameType
payloadany

Returns​

payload is Date

Defined in​

isDate.ts:8


isEmptyArray​

▸ isEmptyArray(payload): payload is []

Returns whether the payload is a an empty array

Parameters​

NameType
payloadany

Returns​

payload is []

Defined in​

isEmptyArray.ts:8


isEmptyObject​

▸ isEmptyObject(payload): payload is Object

Returns whether the payload is a an empty object (excluding special classes or objects with other prototypes)

Parameters​

NameType
payloadany

Returns​

payload is Object

Defined in​

isEmptyObject.ts:8


isEmptyString​

▸ isEmptyString(payload): payload is string

Returns whether the payload is ''

Parameters​

NameType
payloadany

Returns​

payload is string

Defined in​

isEmptyString.ts:6


isError​

▸ isError(payload): payload is Error

Returns whether the payload is an Error

Parameters​

NameType
payloadany

Returns​

payload is Error

Defined in​

isError.ts:8


isFile​

▸ isFile(payload): payload is File

Returns whether the payload is a File

Parameters​

NameType
payloadany

Returns​

payload is File

Defined in​

isFile.ts:8


isFloat​

▸ isFloat(payload): payload is number

Returns whether the payload is a float number

Parameters​

NameType
payloadany

Returns​

payload is number

Defined in​

isFloat.ts:8


isFormData​

▸ isFormData(payload): payload is FormData

Returns whether the payload is a FormData

Parameters​

NameType
payloadany

Returns​

payload is FormData

Defined in​

isFormData.ts:8


isFullArray​

▸ isFullArray(payload): payload is any[]

Returns whether the payload is a an array with at least 1 item

Parameters​

NameType
payloadany

Returns​

payload is any[]

Defined in​

isFullArray.ts:8


isFullObject​

▸ isFullObject(payload): payload is PlainObject

Returns whether the payload is a an empty object (excluding special classes or objects with other prototypes)

Parameters​

NameType
payloadany

Returns​

payload is PlainObject

Defined in​

isFullObject.ts:9


isFullString​

▸ isFullString(payload): payload is string

Returns whether the payload is a string, BUT returns false for ''

Parameters​

NameType
payloadany

Returns​

payload is string

Defined in​

isFullString.ts:8


isFunction​

▸ isFunction(payload): payload is AnyFunction

Returns whether the payload is a function (regular or async)

Parameters​

NameType
payloadany

Returns​

payload is AnyFunction

Defined in​

isFunction.ts:8


isInt​

▸ isInt(payload): payload is number

Returns whether the payload is an integer number

Parameters​

NameType
payloadany

Returns​

payload is number

Defined in​

isInt.ts:8


isMap​

▸ isMap(payload): payload is Map<any, any>

Returns whether the payload is a Map

Parameters​

NameType
payloadany

Returns​

payload is Map<any, any>

Defined in​

isMap.ts:8


isNaNValue​

▸ isNaNValue(payload): payload is number

Returns whether the payload is literally the value NaN (it's NaN and also a number)

Parameters​

NameType
payloadany

Returns​

payload is number

Defined in​

isNaNValue.ts:8


isNegativeNumber​

▸ isNegativeNumber(payload): payload is number

Returns whether the payload is a negative number (but not 0)

Parameters​

NameType
payloadany

Returns​

payload is number

Defined in​

isNegativeNumber.ts:8


isNull​

▸ isNull(payload): payload is null

Returns whether the payload is null

Parameters​

NameType
payloadany

Returns​

payload is null

Defined in​

isNull.ts:8


isNullOrUndefined​

▸ isNullOrUndefined(payload): payload is undefined | null

Returns true whether the payload is null or undefined

Parameters​

NameType
payloadany

Returns​

payload is undefined | null

Defined in​

getType.ts:16


isNumber​

▸ isNumber(payload): payload is number

Returns whether the payload is a number (but not NaN)

This will return false for NaN!!

Parameters​

NameType
payloadany

Returns​

payload is number

Defined in​

isNumber.ts:10


isObject​

▸ isObject(payload): payload is PlainObject

Returns whether the payload is a plain JavaScript object (excluding special classes or objects with other prototypes)

Parameters​

NameType
payloadany

Returns​

payload is PlainObject

Defined in​

isObject.ts:9


isObjectLike​

▸ isObjectLike<T>(payload): payload is T

Returns whether the payload is an object like a type passed in < >

Usage: isObjectLike<{id: any}>(payload) // will make sure it's an object and has an id prop.

Type parameters​

NameType
Textends PlainObject

Parameters​

NameType
payloadany

Returns​

payload is T

Defined in​

isObjectLike.ts:11


isOneOf​

▸ isOneOf<A, B, C>(a, b): TypeGuard<A, B | C>

Type parameters​

Name
A
B
C

Parameters​

NameType
aTypeGuard<A, B>
bTypeGuard<A, C>

Returns​

TypeGuard<A, B | C>

Defined in​

isOneOf.ts:6

▸ isOneOf<A, B, C, D>(a, b, c): TypeGuard<A, B | C | D>

Type parameters​

Name
A
B
C
D

Parameters​

NameType
aTypeGuard<A, B>
bTypeGuard<A, C>
cTypeGuard<A, D>

Returns​

TypeGuard<A, B | C | D>

Defined in​

isOneOf.ts:10

▸ isOneOf<A, B, C, D, E>(a, b, c, d): TypeGuard<A, B | C | D | E>

Type parameters​

Name
A
B
C
D
E

Parameters​

NameType
aTypeGuard<A, B>
bTypeGuard<A, C>
cTypeGuard<A, D>
dTypeGuard<A, E>

Returns​

TypeGuard<A, B | C | D | E>

Defined in​

isOneOf.ts:15

▸ isOneOf<A, B, C, D, E, F>(a, b, c, d, e): TypeGuard<A, B | C | D | E | F>

Type parameters​

Name
A
B
C
D
E
F

Parameters​

NameType
aTypeGuard<A, B>
bTypeGuard<A, C>
cTypeGuard<A, D>
dTypeGuard<A, E>
eTypeGuard<A, F>

Returns​

TypeGuard<A, B | C | D | E | F>

Defined in​

isOneOf.ts:21


isPlainObject​

▸ isPlainObject(payload): payload is PlainObject

Returns whether the payload is a plain JavaScript object (excluding special classes or objects with other prototypes)

Parameters​

NameType
payloadany

Returns​

payload is PlainObject

Defined in​

isPlainObject.ts:8


isPositiveNumber​

▸ isPositiveNumber(payload): payload is number

Returns whether the payload is a positive number (but not 0)

Parameters​

NameType
payloadany

Returns​

payload is number

Defined in​

isPositiveNumber.ts:8


isPrimitive​

▸ isPrimitive(payload): payload is undefined | null | string | number | boolean | symbol

Returns whether the payload is a primitive type (eg. Boolean | Null | Undefined | Number | String | Symbol)

Parameters​

NameType
payloadany

Returns​

payload is undefined | null | string | number | boolean | symbol

Defined in​

isPrimitive.ts:13


isPromise​

▸ isPromise(payload): payload is Promise<any>

Returns whether the payload is a Promise

Parameters​

NameType
payloadany

Returns​

payload is Promise<any>

Defined in​

isPromise.ts:8


isRegExp​

▸ isRegExp(payload): payload is RegExp

Returns whether the payload is a regular expression (RegExp)

Parameters​

NameType
payloadany

Returns​

payload is RegExp

Defined in​

isRegExp.ts:8


isServerNow​

▸ isServerNow(): boolean

Returns​

boolean

Defined in​

isServerNow.ts:7


isSet​

▸ isSet(payload): payload is Set<any>

Returns whether the payload is a Set

Parameters​

NameType
payloadany

Returns​

payload is Set<any>

Defined in​

isSet.ts:8


isString​

▸ isString(payload): payload is string

Returns whether the payload is a string

Parameters​

NameType
payloadany

Returns​

payload is string

Defined in​

isString.ts:8


isSymbol​

▸ isSymbol(payload): payload is symbol

Returns whether the payload is a Symbol

Parameters​

NameType
payloadany

Returns​

payload is symbol

Defined in​

isSymbol.ts:8


isType​

▸ isType<T>(payload, type): payload is T

Does a generic check to check that the given payload is of a given type. In cases like Number, it will return true for NaN as NaN is a Number (thanks javascript!); It will, however, differentiate between object and null

Type parameters​

NameType
Textends AnyFunction | AnyClass

Parameters​

NameType
payloadany
typeT

Returns​

payload is T

Throws

Will throw type error if type is an invalid type

Defined in​

isType.ts:11


isUndefined​

▸ isUndefined(payload): payload is undefined

Returns whether the payload is undefined

Parameters​

NameType
payloadany

Returns​

payload is undefined

Defined in​

isUndefined.ts:8


isWeakMap​

▸ isWeakMap(payload): payload is WeakMap<any, any>

Returns whether the payload is a WeakMap

Parameters​

NameType
payloadany

Returns​

payload is WeakMap<any, any>

Defined in​

isWeakMap.ts:8


isWeakSet​

▸ isWeakSet(payload): payload is WeakSet<any>

Returns whether the payload is a WeakSet

Parameters​

NameType
payloadany

Returns​

payload is WeakSet<any>

Defined in​

isWeakSet.ts:8

location​

AnyQueryParams​

Ƭ AnyQueryParams: undefined | null | Record<string | number, unknown>

Defined in​

location.ts:4


buildUrlQueryString​

▸ buildUrlQueryString<T>(params): string

Get clean query string for URL

It returns the query string with the initial ?

TODO: at some point replace with URLSearchParams,

Type parameters​

NameType
Textends AnyQueryParams

Parameters​

NameType
paramsT

Returns​

string

See

caniuse

Defined in​

buildUrlQueryString.ts:15


changeUrlPath​

▸ changeUrlPath(pathname, state?, replace?): string

Change URL path, ensures initial and ending slashes and normalise eventual consecutive slashes, it uses history.

Parameters​

NameTypeDescription
pathnamestring-
state?object-
replace?booleanReplace URL instead of pushing it in the history stack. By default it pushes it.

Returns​

string

The new cleaned pathname

Defined in​

changeUrlPath.ts:12


getParamAmong​

▸ getParamAmong<T>(raw?, allowedValues?): null | T[number]

Get query parameter as string treating the ParsedUrlQuery result of querystring (used in next.js router and elsewhere)

Type parameters​

NameType
Textends string[]

Parameters​

NameTypeDescription
raw?string | string[]The raw query parameter
allowedValuesTThe list of values (as strings) that the parameter can have, if not one of them null is returned

Returns​

null | T[number]

Defined in​

getParamAmong.ts:14


getParamAsInt​

▸ getParamAsInt<TFallback>(raw?, fallback?): number | TFallback

Get query parameter as integer treating the ParsedUrlQuery result of querystring (used in next.js router and elsewhere)

Type parameters​

NameType
TFallbackextends undefined | null | number

Parameters​

NameTypeDescription
raw?string | string[]The raw query parameter
fallbackTFallbackFallback number, we return null if not provided

Returns​

number | TFallback

Defined in​

getParamAsInt.ts:13


getParamAsString​

▸ getParamAsString(raw?): string

Get query parameter as string treating the ParsedUrlQuery result of querystring (used in next.js router and elsewhere)

Parameters​

NameTypeDescription
raw?string | string[]The raw query parameter

Returns​

string

Defined in​

getParamAsString.ts:12


getUrlHashParams​

▸ getUrlHashParams<T>(hash?): T

It returns the "query params" as an object extracting it from the given hash string or, if not provided, failling back reading the location.hash

Type parameters​

NameType
Textends Record<string | number, unknown>

Parameters​

NameTypeDefault value
hashstring""

Returns​

T

Defined in​

getUrlHashParams.ts:9


getUrlHashPathname​

▸ getUrlHashPathname(hash?): string

It returns the "pathname" cleaned up from the # and the initial slashes extracting it from the given hash string or, if not provided, failling back reading the location.hash

Parameters​

NameTypeDefault value
hashstring""

Returns​

string

Defined in​

getUrlHashPathname.ts:8


getUrlPathnameParts​

▸ getUrlPathnameParts(pathname?): string[]

Get pathname parts

First clean the pathname from the first slash if any then split the pathname in parts, Given a pathname like: "/en/{prefix}/{collection}/{slug}" we obtain [locale, prefix, collection, slug]

Parameters​

NameTypeDefault value
pathnamestring""

Returns​

string[]

Defined in​

getUrlPathnameParts.ts:13


getUrlQueryParams​

▸ getUrlQueryParams<T>(url?): T

Get parsed query parameters as object dictionary (from URL or given query string)

Type parameters​

NameType
Textends Record<string | number, unknown>

Parameters​

NameTypeDescription
url?stringA URL which contains a ?, e.g. ?myparam=x or https://a.com?myparams=x. If not provided it defaults reading the current URL query string with location.search. Through this argument you can use this same function to parse, for instance, the query params of the href of a <a href="..."> HTML tag.

Returns​

T

Defined in​

getUrlQueryParams.ts:14


isExternalUrl​

▸ isExternalUrl(url, currentUrl?): boolean

Is external url compared to the given current URL (if not provided it falls back to location.href)

Parameters​

NameType
urlstring
currentUrl?string

Returns​

boolean

Defined in​

isExternalUrl.ts:10


mergeUrlQueryParams​

▸ mergeUrlQueryParams<T>(oldParams?, newParams?): T

Merge query parameters objects, it mutates the first given object argument

Type parameters​

NameType
Textends AnyQueryParams

Parameters​

NameType
oldParamsRecord<string | number, unknown>
newParamsRecord<string | number, unknown>

Returns​

T

Defined in​

mergeUrlQueryParams.ts:9


normaliseUrl​

▸ normaliseUrl(absoluteUrl?): string

Normalise URL, it works both for absolute and relative URLs

  • replaces too many consecutive slashes (except http{s}://)
  • removes the trailing slash

Parameters​

NameTypeDefault value
absoluteUrlstring""

Returns​

string

See

https://stackoverflow.com/a/40649435/1938970

Defined in​

normaliseUrl.ts:12


normaliseUrlPathname​

▸ normaliseUrlPathname(pathname?): string

Normalise URL pathname (relative URL)

  • replaces too many consecutive slashes
  • removes the trailing slash

Parameters​

NameTypeDefault value
pathnamestring""

Returns​

string

Defined in​

normaliseUrlPathname.ts:11


parseURL​

▸ parseURL(url): null | { hash: string ; host: string ; hostname: string ; href: string = url; pathname: string ; port: string ; protocol: string ; search: string }

Solution without DOM or specific env native methods

Parameters​

NameType
urlstring

Returns​

null | { hash: string ; host: string ; hostname: string ; href: string = url; pathname: string ; port: string ; protocol: string ; search: string }

See

https://stackoverflow.com/a/21553982/1938970

Defined in​

parseURL.ts:7


removeTralingSlash​

▸ removeTralingSlash(urlLike?): string

Strips out the trailing slash

Parameters​

NameTypeDefault value
urlLikestring""

Returns​

string

Defined in​

removeTrailingSlash.ts:6


removeUrlQueryParams​

▸ removeUrlQueryParams(url, paramsToRemove?): string

Remove the given keys from the given URL query parameters

Parameters​

NameTypeDefault value
urlstringundefined
paramsToRemovestring[][]

Returns​

string

Defined in​

removeUrlQueryParams.ts:10


transformToUrlPathname​

▸ transformToUrlPathname(toPathname?): string

Transform string in a URL pathname (relative URL)

  • adds an initial slash
  • encode the string
  • replaces whitespaces with dashes

Parameters​

NameType
toPathname?string

Returns​

string

Defined in​

transformToUrlPathname.ts:12


updateLinkParams​

▸ updateLinkParams($anchor, newParams): string

Update link <a href=""> merging the given new query parameters. it returns the newly created href URL value

Parameters​

NameType
$anchorHTMLAnchorElement
newParamsRecord<string | number, unknown>

Returns​

string

Pure

Defined in​

updateLinkParams.ts:11


updateUrlQueryParams​

▸ updateUrlQueryParams(url, newParams?): string

Update a URL string query parameters merging the given new query parameters

Parameters​

NameType
urlstring
newParamsRecord<string | number, unknown>

Returns​

string

Defined in​

updateUrlQueryParams.ts:11

math​

arraySum​

▸ arraySum(numbers): number

Sum array of numbers

Parameters​

NameType
numbersnumber[]

Returns​

number

Defined in​

arraySum.ts:7


clamp​

▸ clamp(num, min, max): number

Returns a number whose value is limited to the given range.

Parameters​

NameType
numnumber
minnumber
maxnumber

Returns​

number

See

https://stackoverflow.com/a/11409944/1938970

Defined in​

clamp.ts:7


convertRange​

▸ convertRange(num, r1, r2): number

Convert range of a number

e.g. converting number 5 in a scale/range from 0 10 to a scale/range from 50 to 100 would return 75

Parameters​

NameType
numnumber
r1number[]
r2number[]

Returns​

number

Example

convertRange(5, [0, 10], [50, 100]);

See

https://stackoverflow.com/a/14224813

Defined in​

convertRange.ts:15


randomInt​

▸ randomInt(min, max): number

Get random int (min and max included)

Parameters​

NameType
minnumber
maxnumber

Returns​

number

Defined in​

randomInt.ts:6


roundTo​

▸ roundTo(num, decimals?): string

Round to given number of the given number of decimals

Parameters​

NameTypeDefault value
numnumberundefined
decimalsnumber2

Returns​

string

See

https://stackoverflow.com/a/15762794/1938970

Defined in​

roundTo.ts:7

misc​

randomKey​

▸ randomKey<T>(obj): keyof T

Get random key from given object

Type parameters​

NameType
Textends Record<string | number, unknown>

Parameters​

NameType
objT

Returns​

keyof T

See

https://stackoverflow.com/a/15106541/1938970

Defined in​

randomKey.ts:7

native​

forin​

▸ forin<T>(object, cb): void

To easily get typed native for in

Type parameters​

Name
T

Parameters​

NameType
objectT
cb<K>(key: K, value: T[K]) => void

Returns​

void

Defined in​

forin.ts:7


getKeys​

▸ getKeys<T>(obj): keyof T[]

Type safe replacement for Object.keys(myObject) to iterate over a record without loosing the key's types in simple strings.

Type parameters​

NameType
Textends object

Parameters​

NameType
objT

Returns​

keyof T[]

See

https://stackoverflow.com/a/59459000/1938970

Defined in​

getKeys.ts:9


lowercase​

▸ lowercase<T>(str?): Lowercase<T>

Replacement for native toLowercase tyescript ready (type narrowing ready)

Type parameters​

NameType
Textends string

Parameters​

NameType
str?null | T

Returns​

Lowercase<T>

Defined in​

lowercase.ts:6


noop​

▸ noop(): undefined | void

No operation function

Returns​

undefined | void

Defined in​

noop.ts:6


uppercase​

▸ uppercase<T>(str?): Uppercase<T>

Replacement for native toUpperCase tyescript ready (type narrowing ready)

Type parameters​

NameType
Textends string

Parameters​

NameType
str?null | T

Returns​

Uppercase<T>

Defined in​

uppercase.ts:7

object​

areEqual​

▸ areEqual(a, b?): boolean

A simple and quick deep equal objects utility. This is meant to be used solely to deduplicate requests payload and perform comparison on JSON ready objects made of primitives string, number and booleans.

It support nested objects and arrays only.

NB: undefined and null values do not count in the comparison as they are usually meant to be ignored in JSON requestBody payloads.

According to very rudimentary tests this function takes on average between 0.15 ms and 2ms to compare two averaged sizes requet body payloads.

Parameters​

NameType
aComparable
b?Comparable

Returns​

boolean

Defined in​

areEqual.ts:69


forin​

▸ forin<T>(object, cb): void

To easily get typed native for in

Type parameters​

Name
T

Parameters​

NameType
objectT
cb<K>(key: K, value: T[K]) => void

Returns​

void

Defined in​

forin.ts:7


getKeys​

▸ getKeys<T>(obj): keyof T[]

Type safe replacement for Object.keys(myObject) to iterate over a record without loosing the key's types in simple strings.

Type parameters​

NameType
Textends object

Parameters​

NameType
objT

Returns​

keyof T[]

See

https://stackoverflow.com/a/59459000/1938970

Defined in​

getKeys.ts:9


mergeObjects​

▸ mergeObjects<T>(target, ...sources): T

Merge two or more objects together. It mutates the target object.

Type parameters​

NameType
Textends object = object

Parameters​

NameType
targetT
...sourcesPartial<T>[]

Returns​

T

See

https://stackoverflow.com/a/46973278/1938970

Defined in​

mergeObjects.ts:10


objectFlip​

▸ objectFlip<T, U>(input, keyTransformer?): Record<U, T>

Type parameters​

NameType
Textends PropertyKey
Uextends PropertyKey

Parameters​

NameType
inputRecord<T, U>
keyTransformer?(key: string) => T

Returns​

Record<U, T>

Borrows

jacobparis.com

Defined in​

objectFlip.ts:5


objectOmit​

▸ objectOmit<T, Keys>(object, keys): Omit<T, Keys[number]>

Omit object properties by removing the given keys, it returns a new object.

NOTE: most of the time using a normal destructuring assignment is enough, use this utility only when it makes sense.

Type parameters​

NameType
Textends object
Keysextends keyof T[]

Parameters​

NameType
objectT
keysKeys

Returns​

Omit<T, Keys[number]>

Defined in​

objectOmit.ts:10


objectPick​

▸ objectPick<T, Keys>(object, keys): Pick<T, Keys[number]>

Pick object properties by selecting only the given keys, it returns a new object.

Type parameters​

NameType
Textends object
Keysextends keyof T[]

Parameters​

NameType
objectT
keysKeys

Returns​

Pick<T, Keys[number]>

Defined in​

objectPick.ts:7


swapMap​

▸ swapMap<T>(map?): Record<T[keyof T], keyof T>

Swap object map key/value

Type parameters​

NameType
Textends Record<string, string | number | symbol> = Record<string, string | number | symbol>

Parameters​

NameType
mapT

Returns​

Record<T[keyof T], keyof T>

Defined in​

swapMap.ts:6

responsive​

GetMediaQueryWidthResolversBreakpoints​

Ƭ GetMediaQueryWidthResolversBreakpoints: Record<string, number>

Defined in​

getMediaQueryWidthResolvers.ts:4


createPalette​

▸ createPalette<TName, TShades, TColor, TMap>(name, shades): readonly [TMap, Record<`${TName}-${TShades[number][0]}`, string>, TColor[]]

Create palette, this is primarily thought to improve the reuse of a palette definition between TailwindCSS and straight ES imports

Type parameters​

NameType
TNameextends string
TShadesextends PaletteShades
TColorTShades[number][``1``]
TMapPaletteMap<TShades>

Parameters​

NameType
nameTName
shadesTShades

Returns​

readonly [TMap, Record<`${TName}-${TShades[number][0]}`, string>, TColor[]]

An array with: 1) A flat palette map 2) A TailwindCSS ready palette object 3) A flat array of colors (no special sorting, same order as the shades given as argument)

Defined in​

createPalette.ts:25


getMediaQueryWidthResolvers​

▸ getMediaQueryWidthResolvers<TBreakpointsConfig>(customBreakpoints): Object

Type parameters​

NameType
TBreakpointsConfigextends GetMediaQueryWidthResolversBreakpoints

Parameters​

NameType
customBreakpointsTBreakpointsConfig

Returns​

Object

NameType
between(br1: Extract<keyof TBreakpointsConfig, string>, br2?: Extract<keyof TBreakpointsConfig, string>) => string
down(br: Extract<keyof TBreakpointsConfig, string>) => string
max(br: Extract<keyof TBreakpointsConfig, string>) => string
min(br: Extract<keyof TBreakpointsConfig, string>) => string
only(br: Extract<keyof TBreakpointsConfig, string>) => string
up(br: Extract<keyof TBreakpointsConfig, string>) => string

Defined in​

getMediaQueryWidthResolvers.ts:9


getMediaQueryWidthTailwindScreens​

▸ getMediaQueryWidthTailwindScreens(breakpoints): Record<string, { raw: string }>

Parameters​

NameType
breakpointsGetMediaQueryWidthResolversBreakpoints

Returns​

Record<string, { raw: string }>

Defined in​

getMediaQueryWidthTailwindScreens.ts:10

security​

decode​

▸ decode<TReturn>(str): TReturn

Type parameters​

NameType
TReturnextends string

Parameters​

NameType
strstring

Returns​

TReturn

See

https://stackoverflow.com/a/22405578/9122820

Defined in​

decode.ts:5


encode​

▸ encode<TReturn>(str): TReturn

Type parameters​

NameType
TReturnextends string

Parameters​

NameType
strstring

Returns​

TReturn

See

https://stackoverflow.com/a/22405578/9122820

Defined in​

encode.ts:5


getNonce​

▸ getNonce(): null | string

Returns​

null | string

See

https://github.com/styled-components/styled-components/blob/main/packages/styled-components/src/utils/nonce.ts

Defined in​

getNonce.ts:9

ssr​

isBrowser​

• Const isBrowser: boolean

Defined in​

isBrowser.ts:5


isServer​

• Const isServer: boolean = !isBrowser

Defined in​

isServer.ts:7


isBrowserNow​

▸ isBrowserNow(): boolean

Returns​

boolean

Defined in​

isBrowserNow.ts:7


isServerNow​

▸ isServerNow(): boolean

Returns​

boolean

Defined in​

isServerNow.ts:7

tailwind​

createPalette​

▸ createPalette<TName, TShades, TColor, TMap>(name, shades): readonly [TMap, Record<`${TName}-${TShades[number][0]}`, string>, TColor[]]

Create palette, this is primarily thought to improve the reuse of a palette definition between TailwindCSS and straight ES imports

Type parameters​

NameType
TNameextends string
TShadesextends PaletteShades
TColorTShades[number][``1``]
TMapPaletteMap<TShades>

Parameters​

NameType
nameTName
shadesTShades

Returns​

readonly [TMap, Record<`${TName}-${TShades[number][0]}`, string>, TColor[]]

An array with: 1) A flat palette map 2) A TailwindCSS ready palette object 3) A flat array of colors (no special sorting, same order as the shades given as argument)

Defined in​

createPalette.ts:25


getMediaQueryWidthTailwindScreens​

▸ getMediaQueryWidthTailwindScreens(breakpoints): Record<string, { raw: string }>

Parameters​

NameType
breakpointsGetMediaQueryWidthResolversBreakpoints

Returns​

Record<string, { raw: string }>

Defined in​

getMediaQueryWidthTailwindScreens.ts:10

text​

AccentsSet​

Ƭ AccentsSet: [string, string]

First value is the to, second is from, from which chars do we translates to

Defined in​

accentSets.ts:6


accentsSets​

• Const accentsSets: AccentsSet[]

Accent sets

Resources

Defined in​

accentSets.ts:17


capitalize​

▸ capitalize<T>(string?): Capitalize<T>

Capitalize first letter of the given string.

Type parameters​

NameType
Textends string

Parameters​

NameType
string?null | T

Returns​

Capitalize<T>

Resources

Defined in​

capitalize.ts:8


removeAccents​

▸ removeAccents(text?, sets?): string

Parameters​

NameTypeDefault value
textstring""
setsAccentsSet[]accentsSets

Returns​

string

Defined in​

removeAccents.ts:6


slugify​

▸ slugify(text, separator?): string

Slugify a text

  • replaces the accented letters
  • replaces the punctuation with dashes

Parameters​

NameTypeDefault value
textstringundefined
separatorstring"-"

Returns​

string

Borrows

mathewbyrne's gist

Defined in​

slugify.ts:14


titleCase​

▸ titleCase(input?): string

Parameters​

NameType
input?null | string

Returns​

string

Borrows

blakeembrey/change-case

License

Blake Embrey (hello@blakeembrey.com)

Defined in​

titleCase.ts:7


truncate​

▸ truncate(input, length): string

Truncate string

Parameters​

NameType
inputundefined | null | string
lengthnumber

Returns​

string

Defined in​

truncate.ts:6


uppercase​

▸ uppercase<T>(str?): Uppercase<T>

Replacement for native toUpperCase tyescript ready (type narrowing ready)

Type parameters​

NameType
Textends string

Parameters​

NameType
str?null | T

Returns​

Uppercase<T>

Defined in​

uppercase.ts:7

uid​

uid​

▸ uid(prefix?): string

Super basic UID increment-based generator

Parameters​

NameTypeDefault value
prefixstring"id"

Returns​

string

Defined in​

uid.ts:8


uuid​

▸ uuid(): string

Uuid, tiny custom helper instead of node's uuid/v4

Returns​

string

See

https://stackoverflow.com/a/2117523/1938970

Defined in​

uuid.ts:7


uuidNumeric​

▸ uuidNumeric(): number

Returns​

number

See

https://stackoverflow.com/a/18048162/1938970

Defined in​

uuidNumeric.ts:5