Last active
May 24, 2021 23:14
-
-
Save karol-majewski/b42dece0066576318088c2ea5362bc26 to your computer and use it in GitHub Desktop.
Memoize a function based on a custom equality function (+ use case for unique symbol)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type AnyFunction = (...args: any[]) => any; | |
/** | |
* Creates a memoized function that preserves reference equality based on a predicate function. | |
* | |
* @param fn Function which return value will be memoized. | |
* @param isEqual Should return `true` when two objects are considered identical. | |
* | |
* @example | |
* | |
* ```ts | |
* const fn = memoize(() => ({ foo: 1, nonce: 2 }), (previous, next) => previous.foo === next.foo); | |
* | |
* const first = fn(); | |
* const second = fn(); | |
* | |
* first === second; // true | |
* ``` | |
*/ | |
export function memoize<T extends AnyFunction>( | |
fn: T, | |
isEqual: (previous: ReturnType<T>, next: ReturnType<T>) => boolean = Object.is | |
): (...params: Parameters<T>) => ReturnType<T> { | |
const nothing: unique symbol = Symbol(); | |
let previous: ReturnType<T> | typeof nothing = nothing; | |
return (...params: Parameters<T>) => { | |
const current = fn(params); | |
if (previous === nothing || !isEqual(previous, current)) { | |
previous = current; | |
return current; | |
} | |
return previous; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use to memoize the value of the state variable used in
React.Context
:shouldComponentUpdate
can also be used.For function components, use this.