Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input
$ npm install --save mem
const mem = require('mem'); let i = 0; const counter = () => ++i; const memoized = mem(counter); memoized('foo'); //=> 1 // cached as it's the same arguments memoized('foo'); //=> 1 // not cached anymore as the arguments changed memoized('bar'); //=> 2 memoized('bar'); //=> 2
const mem = require('mem'); let i = 0; const counter = () => Promise.resolve(++i); const memoized = mem(counter); memoized().then(a => { console.log(a); //=> 1 memoized().then(b => { // the return value didn't increase as it's cached console.log(b); //=> 1 }); });
const mem = require('mem'); const got = require('got'); const memGot = mem(got, {maxAge: 1000}); memGot('sindresorhus.com').then(() => { // this call is cached memGot('sindresorhus.com').then(() => { setTimeout(() => { // this call is not cached as the cache has expired memGot('sindresorhus.com').then(() => {}); }, 2000); }); });
Type: Function
Function to be memoized.
Type: number
Default: Infinity
Milliseconds until the cache expires.
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)
.
Type: Object
Default: new Map()
Use a different cache storage. Must implement the following methods: .has(key)
, .get(key)
, .set(key, value)
, and optionally .clear()
. You could for example use a WeakMap
instead.
Clear all cached data of a memoized function.
Type: Function
Memoized function.
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.
const mem = require('mem'); const StatsMap = require('stats-map'); const got = require('got'); const cache = new StatsMap(); const memGot = mem(got, {cache}); memGot('sindresorhus.com') .then(() => memGot('sindresorhus.com')) .then(() => memGot('sindresorhus.com')); console.log(cache.stats); //=> {hits: 2, misses: 1}
MIT © Sindre Sorhus