Memoize a function using a custom cache and a key formatter
$ npm install memoize-with
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
})()
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 |
MIT © saxjst