Skip to main content

@rtorcato/js-common / functions

functions

Functions

once()

once<T>(fn): T

Defined in: functions/index.ts:17

Returns a function that only calls the original function once.

Example

let calls = 0
const init = once(() => ++calls)
init() // 1
init() // 1 (cached, not called again)
calls // 1

Type Parameters

T

T extends (...args) => any

Parameters

fn

T

The function to wrap.

Returns

T


debounce()

debounce<T>(fn, wait): (...args) => void

Defined in: functions/index.ts:46

Returns a debounced version of a function. The wrapper defers the call, so it always returns undefined — never fn's return value.

Example

const search = debounce((term: string) => console.log(term), 300)
search('a')
search('ab')
search('abc') // only 'abc' is logged, 300ms after the last call

Type Parameters

T

T extends (...args) => void

Parameters

fn

T

The function to debounce.

wait

number

Milliseconds to wait.

Returns

(...args) => void


throttle()

throttle<T>(fn, wait): (...args) => void

Defined in: functions/index.ts:74

Returns a throttled version of a function. The wrapper drops calls inside the window, so it always returns undefined — never fn's return value.

Example

const onScroll = throttle(() => console.log(window.scrollY), 100)
window.addEventListener('scroll', onScroll)
// fires at most once every 100ms, leading edge first

Type Parameters

T

T extends (...args) => void

Parameters

fn

T

The function to throttle.

wait

number

Milliseconds to wait between calls.

Returns

(...args) => void


compose()

compose<T>(...fns): (arg) => T

Defined in: functions/index.ts:93

Composes functions from right to left.

Type Parameters

T

T

Parameters

fns

...(arg) => T[]

Functions to compose.

Returns

(arg) => T


pipe()

pipe<T>(...fns): (arg) => T

Defined in: functions/index.ts:102

Pipes functions from left to right.

Type Parameters

T

T

Parameters

fns

...(arg) => T[]

Functions to pipe.

Returns

(arg) => T