1.0.0 • Published 4 years ago

memoize-with v1.0.0

Weekly downloads
2
License
Apache 2.0
Repository
github
Last release
4 years ago

memoize-with

Build Status Coverage Status Maintainability Language grade: JavaScript tested with jest code style: prettier

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

ParamTypeDescription
cacheObjectobject to store values into
keyFormaterFunctionfunction that generate the cache key
fnFunctionfunction to memoize

License

MIT © saxjst