cached-function
A Node.js module that wraps a function and caches its return value for any given set of arguments. When those same arguments are used again, it pulls from the cache.
- Cached values can be cleared manually or can be configured to expire automatically.
- In addition to caching regular functions, the module can also cache class methods and getters.
Installation
npm install cached-function --save
Usage Examples
const CachedFunction = { console // Do the download return 'data'} // Returns 'data' and outputs "Downloading..." // Returns 'data' but no console output
It caches the return value for any given set of arguments:
const CachedFunction = let add = // 4 // returns 4 from the cache
Class Methods
You can easily modify a prototype to cache a particular method for all instantiated objects:
const CachedFunction = { thisvalue = value } { console return thisvalue + suffix } // Cache the data methodTestClassprototypedata = const test = 'value'testdata123 // returns 'value123' and logs to the consoletestdata123 // returns 'value123' but does NOT log to the consoleCachedFunction // clears the cached return valuetestdata123 // returns 'value123' and logs to the console
Property Getters
The cacheGetter()
function makes it easy to implement caching on a property getter:
const CachedFunction = { thisvalue = value } { console return thisvalue } CachedFunction const test = 'value'testdata // returns 'value' and logs to the consoletestdata // returns 'value' but does NOT log to the consoleCachedFunction // clears the cached return valuetestdata // returns 'value' and logs to the console
Manual Cache Clearing
The clearCache()
function can be used to flush the cache manually.
const CachedFunction = let add = // 4 // returns 4 from the cache // 10 // returns 10 from the cache // Clears the cached return value for the given arguments:CachedFunction // recalculates: 4 // still cached: 10
Automatic Cache Expiry
Cached return values can be set to expire after a given number of milliseconds. After a value expires, future calls with those arguments will trigger the underlying function once again.
// Each cached return value will have a lifetime of 10 seconds.func =
Argument Match Modes
By default, the CachedFunction
will return a cached return value for a given set of arguments only if those arguments are identical. But if you want, you can disable strict-match mode and can compare arguments by their serialization.
const CachedFunction = { console} const strict = // Default behavior // Logs to the console // Still logs to the console. The cache is not invoked because it's technically a different array. const loose = // Logs to the console // Doesn't log to the console. Pulls from the cache, because the array's serialization is identical.