memoizeOne
A simple memoization library which only remembers the latest invokation
DOCS: Work in progress
Rationale
Cache invalidation is hard:
There are only two hard things in Computer Science: cache invalidation and naming things.
Phil Karlton
So keep things simple and just use a cache size of one.
Unlike other memoization libraries, memoizeOne
only remembers the latest arguments. No need to worry about cache busting mechanisms such as maxAge
, maxSize
, exlusions
and so on which can be prone to memory leaks. memoizeOne
simply remembers the last arguments, and if the function is next called with the same arguments then it returns the previous result.
Usage
Standard usage
import memoizeOne from 'memoize-one';
const add = (a, b) => a + b;
const memoizedAdd = memoizeOne(add);
memoizedAdd(1, 2);
memoizedAdd(1, 2);
memoizedAdd(2, 3);
memoizedAdd(2, 3);
memoizedAdd(1, 2);
Custom equality function
You can also pass in a custom function for checking the equality of two items.
import memoizeOne from 'memoize-one';
import deepEqual from 'lodash.isEqual';
const identity = x => x;
const defaultMemoization = memoizeOne(identity);
const customMemoization = memoizeOne(identity, deepEqual);
const result1 = defaultMemoization({foo: 'bar'});
const result2 = defaultMemoization({foo: 'bar'});
result1 === result2
const result3 = customMemoization({foo: 'bar'});
const result4 = customMemoization({foo: 'bar'});
result3 === result4
Installation
yarn add memoize-one
npm install memoize-one --save
Other features
Correctly supports this
binding
Custom equality function
Code health