Functools
Utilities for working with functions in JavaScript, with TypeScript.
(Inspired by functools of the same name)
Installation
npm install functools --save
Usage
identity<T>(arg: T) => T
Always returns the same value that was used as the argument.
identity(42)
memoize<T, U>(fn: (x: T) => U, cache?: Cache) => (x: T) => U
Optimize a function to speed up consecutive calls by caching the result of calls with identical input arguments. The cache can be overridden for features such as an LRU cache.
let i = 0
const fn = memoize(() => ++i)
fn('foo')
fn('foo')
fn('bar')
fn('bar')
See also: memoize0
for zero-length function arguments.
prop<K>(key: K) => (obj: T) => T[K]
Return a function that fetches key
from its operand.
prop('foo')({ foo: 123 })
invoke<K, A, T>(key: K, ...args: A) => (obj: T) => ReturnType<T[K]>
Return a function that calls the method name on its operand. If additional arguments are given, they will be given to the method as well.
invoke('add', 5, 5)({ add: (a, b) => a + b })
throttle(fn: () => void, ms: number, leading = true) => () => void
Wrap a function to rate-limit the function executions to once every ms
milliseconds.
let i = 0
const fn = throttle(() => ++i, 100)
fn()
fn()
fn()
setTimeout(() => , 200)
Tip: Use fn.clear
and fn.flush
for finer execution control.
fn.clear
Unconditionally clears the current timeoutfn.flush
When fn
is pending, executes fn()
and starts a new interval
TypeScript
This module uses TypeScript and publishes type definitions on NPM.
License
Apache 2.0