memoizeWith.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import _arity from "./internal/_arity.js";
  2. import _curry2 from "./internal/_curry2.js";
  3. import _has from "./internal/_has.js";
  4. /**
  5. * Takes a string-returning function `keyGen` and a function `fn` and returns
  6. * a new function that returns cached results for subsequent
  7. * calls with the same arguments.
  8. *
  9. * When the function is invoked, `keyGen` is applied to the same arguments
  10. * and its result becomes the cache key. If the cache contains something
  11. * under that key, the function simply returns it and does not invoke `fn` at all.
  12. *
  13. * Otherwise `fn` is applied to the same arguments and its return value
  14. * is cached under that key and returned by the function.
  15. *
  16. * Care must be taken when implementing `keyGen` to avoid key collision,
  17. * or if tracking references, memory leaks and mutating arguments.
  18. *
  19. * @func
  20. * @memberOf R
  21. * @since v0.24.0
  22. * @category Function
  23. * @sig (*... -> String) -> (*... -> a) -> (*... -> a)
  24. * @param {Function} keyGen The function to generate the cache key.
  25. * @param {Function} fn The function to memoize.
  26. * @return {Function} Memoized version of `fn`.
  27. * @example
  28. * const withAge = memoizeWith(o => `${o.birth}/${o.death}`, ({birth, death}) => {
  29. * // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
  30. * // keyGen fn
  31. * console.log(`computing age for ${birth}/${death}`);
  32. * return ({birth, death, age: death - birth});
  33. * });
  34. *
  35. * withAge({birth: 1921, death: 1999});
  36. * //=> LOG: computing age for 1921/1999
  37. * //=> {birth: 1921, death: 1999, age: 78} (returned from fn)
  38. *
  39. * withAge({birth: 1921, death: 1999});
  40. * //=> {birth: 1921, death: 1999, age: 78} (returned from cache)
  41. */
  42. var memoizeWith =
  43. /*#__PURE__*/
  44. _curry2(function memoizeWith(keyGen, fn) {
  45. var cache = {};
  46. return _arity(fn.length, function () {
  47. var key = keyGen.apply(this, arguments);
  48. if (!_has(key, cache)) {
  49. cache[key] = fn.apply(this, arguments);
  50. }
  51. return cache[key];
  52. });
  53. });
  54. export default memoizeWith;