Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork54
Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input
License
sindresorhus/memoize
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input
Memory is automatically released when an item expires or the cache is cleared.
By default,only the memoized function's first argument is considered via strict equality comparison. If you need to cache multiple arguments or cacheobjectsby value, have a look at alternativecaching strategies below.
If you want to memoize Promise-returning functions (likeasync functions), you might be better served byp-memoize.
npm install memoize
importmemoizefrom'memoize';letindex=0;constcounter=()=>++index;constmemoized=memoize(counter);memoized('foo');//=> 1// Cached as it's the same argumentmemoized('foo');//=> 1// Not cached anymore as the argument changedmemoized('bar');//=> 2memoized('bar');//=> 2// Only the first argument is considered by defaultmemoized('bar','foo');//=> 2
But you might want to usep-memoize for more Promise-specific behaviors.
importmemoizefrom'memoize';letindex=0;constcounter=async()=>++index;constmemoized=memoize(counter);console.log(awaitmemoized());//=> 1// The return value didn't increase as it's cachedconsole.log(awaitmemoized());//=> 1
importmemoizefrom'memoize';importgotfrom'got';importdelayfrom'delay';constmemoizedGot=memoize(got,{maxAge:1000});awaitmemoizedGot('https://sindresorhus.com');// This call is cachedawaitmemoizedGot('https://sindresorhus.com');awaitdelay(2000);// This call is not cached as the cache has expiredawaitmemoizedGot('https://sindresorhus.com');
By default, only the first argument is compared via exact equality (===) to determine whether a call is identical.
importmemoizefrom'memoize';constpow=memoize((a,b)=>Math.pow(a,b));pow(2,2);// => 4, stored in cache with the key 2 (number)pow(2,3);// => 4, retrieved from cache at key 2 (number), it's wrong
You will have to use thecache andcacheKey options appropriate to your function. In this specific case, the following could work:
importmemoizefrom'memoize';constpow=memoize((a,b)=>Math.pow(a,b),{cacheKey:arguments_=>arguments_.join(',')});pow(2,2);// => 4, stored in cache with the key '2,2' (both arguments as one string)pow(2,3);// => 8, stored in cache with the key '2,3'
More advanced examples follow.
If your function accepts an object, it won't be memoized out of the box:
importmemoizefrom'memoize';constheavyMemoizedOperation=memoize(heavyOperation);heavyMemoizedOperation({full:true});// Stored in cache with the object as keyheavyMemoizedOperation({full:true});// Stored in cache with the object as key, again// The objects appear the same, but in JavaScript, they're different objects
You might want to serialize or hash them, for example usingJSON.stringify or something likeserialize-javascript, which can also serializeRegExp,Date and so on.
importmemoizefrom'memoize';constheavyMemoizedOperation=memoize(heavyOperation,{cacheKey:JSON.stringify});heavyMemoizedOperation({full:true});// Stored in cache with the key '[{"full":true}]' (string)heavyMemoizedOperation({full:true});// Retrieved from cache
The same solution also works if it accepts multiple serializable objects:
importmemoizefrom'memoize';constheavyMemoizedOperation=memoize(heavyOperation,{cacheKey:JSON.stringify});heavyMemoizedOperation('hello',{full:true});// Stored in cache with the key '["hello",{"full":true}]' (string)heavyMemoizedOperation('hello',{full:true});// Retrieved from cache
If your function accepts multiple arguments that aren't supported byJSON.stringify (e.g. DOM elements and functions), you can instead extend the initial exact equality (===) to work on multiple arguments usingmany-keys-map:
importmemoizefrom'memoize';importManyKeysMapfrom'many-keys-map';constaddListener=(emitter,eventName,listener)=>emitter.on(eventName,listener);constaddOneListener=memoize(addListener,{cacheKey:arguments_=>arguments_,// Use *all* the arguments as keycache:newManyKeysMap()// Correctly handles all the arguments for exact equality});addOneListener(header,'click',console.log);// `addListener` is run, and it's cached with the `arguments` array as keyaddOneListener(header,'click',console.log);// `addListener` is not run again because the arguments are the sameaddOneListener(mainContent,'load',console.log);// `addListener` is run, and it's cached with the `arguments` array as key
Better yet, if your function’s arguments are compatible withWeakMap, you should usedeep-weak-map instead ofmany-keys-map. This will help avoid memory leaks.
Type:Function
The function to be memoized.
Type:object
Type:number |Function
Default:Infinity
Example:arguments_ => arguments_ < new Date() ? Infinity : 60_000
Milliseconds until the cache entry expires.
If a function is provided, it receives the arguments and must return the max age.
0or negative values: Do not cache the resultInfinity: Cache indefinitely (no expiration)- Positive finite number: Cache for the specified milliseconds
Type:Function
Default:arguments_ => arguments_[0]
Example:arguments_ => JSON.stringify(arguments_)
Determines the cache key for storing the result based on the function arguments. By default,only the first argument is considered.
AcacheKey function can return any type supported byMap (or whatever structure you use in thecache option).
Refer to thecaching strategies section for more information.
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 aWeakMap instead orquick-lru for a LRU cache.
Refer to thecaching strategies section for more information.
Returns adecorator to memoize class methods or static class methods.
Notes:
- Only class methods and getters/setters can be memoized, not regular functions (they aren't part of the proposal);
- OnlyTypeScript’s decorators are supported, notBabel’s, which use a different version of the proposal;
- Being an experimental feature, they need to be enabled with
--experimentalDecorators; follow TypeScript’s docs.
Type:object
Same as options formemoize().
import{memoizeDecorator}from'memoize';classExample{index=0@memoizeDecorator()counter(){return++this.index;}}classExampleWithOptions{index=0@memoizeDecorator({maxAge:1000})counter(){return++this.index;}}
Clear all cached data of a memoized function.
Type:Function
The memoized function.
Check if a specific set of arguments is cached for a memoized function.
Returnstrue if the arguments are cached and not expired,false otherwise.
Uses the same argument processing as the memoized function, including any customcacheKey function.
importmemoize,{memoizeIsCached}from'memoize';constexpensive=memoize((a,b)=>a+b,{cacheKey:JSON.stringify});expensive(1,2);memoizeIsCached(expensive,1,2);//=> truememoizeIsCached(expensive,3,4);//=> false
Type:Function
The memoized function.
The arguments to check.
If you want to know how many times your cache had a hit or a miss, you can make use ofstats-map as a replacement for the default cache.
importmemoizefrom'memoize';importStatsMapfrom'stats-map';importgotfrom'got';constcache=newStatsMap();constmemoizedGot=memoize(got,{cache});awaitmemoizedGot('https://sindresorhus.com');awaitmemoizedGot('https://sindresorhus.com');awaitmemoizedGot('https://sindresorhus.com');console.log(cache.stats);//=> {hits: 2, misses: 1}
- p-memoize - Memoize promise-returning & async functions
About
Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.