index.js 1.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. const mimicFn = require('mimic-fn');
  3. const cacheStore = new WeakMap();
  4. const defaultCacheKey = function (x) {
  5. if (arguments.length === 1 && (x === null || x === undefined || (typeof x !== 'function' && typeof x !== 'object'))) {
  6. return x;
  7. }
  8. return JSON.stringify(arguments);
  9. };
  10. module.exports = (fn, opts) => {
  11. opts = Object.assign({
  12. cacheKey: defaultCacheKey,
  13. cache: new Map()
  14. }, opts);
  15. const memoized = function () {
  16. const cache = cacheStore.get(memoized);
  17. const key = opts.cacheKey.apply(null, arguments);
  18. if (cache.has(key)) {
  19. const c = cache.get(key);
  20. if (typeof opts.maxAge !== 'number' || Date.now() < c.maxAge) {
  21. return c.data;
  22. }
  23. }
  24. const ret = fn.apply(null, arguments);
  25. cache.set(key, {
  26. data: ret,
  27. maxAge: Date.now() + (opts.maxAge || 0)
  28. });
  29. return ret;
  30. };
  31. mimicFn(memoized, fn);
  32. cacheStore.set(memoized, opts.cache);
  33. return memoized;
  34. };
  35. module.exports.clear = fn => {
  36. const cache = cacheStore.get(fn);
  37. if (cache && typeof cache.clear === 'function') {
  38. cache.clear();
  39. }
  40. };