UNPKG

@mightyplow/jslib

Version:

js helpers library

38 lines (31 loc) 1.08 kB
import removeProp from '../object/removeProp'; /** * Caches a function result for a specified time. * * @memberOf function * * @param {function} fn - the function of which the result should be cached * @param {number} [timeout] - the time in ms which tells the time after which the results should be deleted from the cache * @returns {function} */ var memoize = function memoize(fn, timeout) { var cache = {}; var removeCachedValue = function removeCachedValue(key) { return function () { return removeProp(cache)(key); }; }; return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var key = JSON.stringify(args || []); if (!(key in cache)) { cache[key] = fn.apply(undefined, args); // clear cached value after timeout !isNaN(timeout) && setTimeout(removeCachedValue(key), timeout); } return cache[key]; }; }; export default memoize;