memoize-with
v1.0.0
Published
Memoize a function using a custom cache and a key formatter
Downloads
2
Readme
memoize-with
Memoize a function using a custom cache and a key formatter
Install
$ npm install memoize-with
Usage
const memoizeWith = require("memoize-with");
let customCache = {
obj: {},
get: async (key) => customCache.obj[key],
set: async (key, value) => customCache.obj[key] = value
};
// random function to create a key for the cache
const arrayToString = array => JSON.stringify(array):
let count = 0;
// random function to memoize
const add = (x, y) => {
count += 1;
return x + y;
}
const cachedAdd = memoizeWith(customCache, arrayToString, add);
(async () => {
await cachedAdd(2, 2); //=> 4
await cachedAdd(2, 2); //=> 4
await cachedAdd(2, 2); //=> 4
count; //=> 1
})()
API
memoizeWith(cache, keyFormater, fn) ⇒ Function
Memoize a function using a custom cache and a key formatter
Returns: Function - memoized version of fn
| Param | Type | Description | | ----------- | --------------------- | ------------------------------------ | | cache | Object | object to store values into | | keyFormater | Function | function that generate the cache key | | fn | Function | function to memoize |
License
MIT © saxjst