mem
Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input
Install
$ npm install mem
Usage
const mem = ; let i = 0;const counter = ++i;const memoized = ; ;//=> 1 // Cached as it's the same arguments;//=> 1 // Not cached anymore as the arguments changed;//=> 2 ;//=> 2
Works fine with promise returning functions
const mem = ; let i = 0;const counter = Promise;const memoized = ; ;
const mem = ;const got = ;const memGot = ; ;
API
mem(fn, [options])
fn
Type: Function
Function to be memoized.
options
maxAge
Type: number
Default: Infinity
Milliseconds until the cache expires.
cacheKey
Type: Function
Determines the cache key for storing the result based on the function arguments. By default, if there's only one argument and it's a primitive, it's used directly as a key, otherwise it's all the function arguments JSON stringified as an array.
You could for example change it to only cache on the first argument x => JSON.stringify(x)
.
cache
Type: Object
Default: new Map()
Use a different cache storage. Must implement the following methods: .has(key)
, .get(key)
, .set(key, value)
, .delete(key)
, and optionally .clear()
. You could for example use a WeakMap
instead or quick-lru
for a LRU cache.
cachePromiseRejection
Type: boolean
Default: false
Cache rejected promises.
mem.clear(fn)
Clear all cached data of a memoized function.
fn
Type: Function
Memoized function.
Tips
Cache statistics
If you want to know how many times your cache had a hit or a miss, you can make use of stats-map as a replacement for the default cache.
Example
const mem = ;const StatsMap = ;const got = ; const cache = ;const memGot = ; ; console;//=> {hits: 2, misses: 1}
Related
- p-memoize - Memoize promise-returning & async functions
License
MIT © Sindre Sorhus