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 = require('cached-function')
function downloadData() {
console.log('Downloading...')
return 'data'
}
CachedFunction(downloadData)()
CachedFunction(downloadData)()
It caches the return value for any given set of arguments:
const CachedFunction = require('cached-function')
let add = CachedFunction((a, b) => a + b)
add(2, 2)
add(2, 2)
Class Methods
You can easily modify a prototype to cache a particular method for all instantiated objects:
const CachedFunction = require('cached-function')
class TestClass {
constructor (value) {
this.value = value
}
data (suffix) {
console.log('The data method was called')
return this.value + suffix
}
}
TestClass.prototype.data = CachedFunction(TestClass.prototype.data)
const test = new TestClass('value')
test.data(123)
test.data(123)
CachedFunction.clearCache(test, 'data', [123])
test.data(123)
Property Getters
The cacheGetter()
function makes it easy to implement caching on a property getter:
const CachedFunction = require('cached-function')
class TestClass {
constructor (value) {
this.value = value
}
get data () {
console.log('The data getter was called')
return this.value
}
}
CachedFunction.cacheGetter(TestClass, 'data', {ttl: 5000})
const test = new TestClass('value')
test.data
test.data
CachedFunction.clearCache(test, 'data')
test.data
Manual Cache Clearing
The clearCache()
function can be used to flush the cache manually.
const CachedFunction = require('cached-function')
let add = CachedFunction((a, b) => a + b)
add(2, 2)
add(2, 2)
add(5, 5)
add(5, 5)
CachedFunction.clearCache(add, [2, 2])
add(2, 2)
add(5, 5)
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.
func = CachedFunction(func, {ttl: 10000})
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 = require('cached-function')
function callback (stringArg, arrayArg) {
console.log('Function called')
}
const strict = CachedFunction(callback)
strict('test', [1, 2, 3])
strict('test', [1, 2, 3])
const loose = CachedFunction(callback, {strictArgMatch: false})
loose('test', [1, 2, 3])
loose('test', [1, 2, 3])