Utilities

Type alias Obj

Object Map Interface.

cache (fn: (args: Args): T): (args: Args): NonNullable<T>

Function wrapper that modifies a function to cache its return values. This is useful for performance intensive functions which are called repeatedly with the same arguments. However it can reduce performance for functions which are always called with different arguments. Note that argument comparison does not work with Objects or nested arrays.

Name Type Default Description
fn (args: Args): T    

deepExtend (obj1: any, obj2: any, arrayMergeFn: (a: Array<unknown>, b: Array<unknown>): Array<unknown>): void

Deep extends obj1 with obj2, using a custom array merge function.

Name Type Default Description
obj1 any    
obj2 any    
arrayMergeFn (a: Array<unknown>, b: Array<unknown>): Array<unknown>  

defer (): {promise: Promise<T>, reject: (reason: unknown): void, resolve: (value: T|PromiseLike<T>): void}

Creates a new promise together with functions to resolve or reject.

delay (fn: (): void, t: number): number

Replacement for setTimeout() that is synchronous for time 0.

Name Type Default Description
fn (): void    
t number 0  

isOneOf (x: T, values: Array<T>): boolean

Checks if x is strictly equal to any one of the following arguments.

Name Type Default Description
x T    
values Array<T>    

run (val: T|(args: Array<S>): T, args: Array<S>): T

Executes a function or returns the default value.

Name Type Default Description  
val T (args: Array<S>): T    
args Array<S>      

safeToJSON (str: |string, fallback: T, allowedKeys: Array<string>): undefined|T

Safe wrapper for JSON.parse.

Name Type Default Description  
str   string    
fallback T      
allowedKeys Array<string>      

throttle (fn: (args: Args): void, t: number, forceDelay: boolean): (args: Args): void

Function wrapper that prevents a function from being executed more than once every t ms. This is particularly useful for optimising callbacks for continues events like scroll, resize or slider move. Setting forceDelay to true means that even the first function call is after the minimum timout, rather than instantly.

Name Type Default Description
fn (args: Args): void    
t number 0  
forceDelay boolean false  

uid (n: number): string

Creates a random UID string of a given length.

Name Type Default Description
n number 10  

wait (t: number): Promise<void>

Returns a promise that resolves after a fixed time.

Name Type Default Description
t number    

Copyright © 2024 Mathigon.org