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 supplied to it.
; //=> 42
always<T>(arg: T) => () => T
Returns a function that always returns the same value supplied to it.
; //=> 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 = ; ; //=> 1; //=> 1 ; //=> 2; //=> 2
memoize0<T>(fn: () => T): () => T
Memoize the result of fn
after the first invocation.
let i = 0;const fn = ; ; // => 1; // => 1; // => 1
memoizeOne<T, R>(fn: (...args: T) => R) => (...args: T) => R
Memoize the result of a function based on the most recent arguments.
let i = 0;const fn = ; ; //=> 1; //=> 1 ; //=> 2; //=> 2 ; //=> 3; //=> 3
prop<K>(key: K) => (obj: T) => T[K]
Return a function that fetches key
from its operand.
foo: 123 ; //=> 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.
a + b ; //=> 10
throttle<T>(fn: (...args: T) => void, ms: number, { leading, trailing, debounce }) => (...args: T) => void
Wrap a function to rate-limit the function executions to once every ms
milliseconds.
let i = 0const fn = // i == 1 // i == 1 // i == 1
Tip: Use fn.clear
and fn.flush
for finer execution control.
fn.clear
Unconditionally clears the current timeoutfn.flush
Whenfn
is pending, executesfn()
and starts a new interval
spread<T, R>(fn: (...args: T) => R) => (args: T) => R
Given a fn
, return a wrapper that accepts an array of fn
arguments.
Promiseall1 2 3;
flip<T1, T2, R>(fn: (arg1: T1, arg2: T2) => R) => (arg2: T2, arg1: T1) => R
Flip a binary fn
argument order.
5 10; //=> 5
partial<T, U, R>(fn: (...args1: T, ...args2: U) => R) => (...args: U) => R
Returns a partially applied fn
with the supplied arguments.
5; //=> 5
sequence<T>(...fns: Array<(input: T) => T>) => (input: T) => T
Left-to-right function composition.
5; //=> 75
compose<T>(...fns: Array<(input: T) => T>) => (input: T) => T
Right-to-left function composition.
5; //=> 35
nary<T, R>(n: number, fn: (...args: T) => R) => (...args: T) => R
Fix the number of receivable arguments in origFn
to n
.
"1" "2" "3"; //=> [1, 2, 3]
TypeScript
This module uses TypeScript and publishes type definitions on NPM.
License
Apache 2.0