[d24f17c] | 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 |
|
---|
| 43 | var memoizeWith =
|
---|
| 44 | /*#__PURE__*/
|
---|
| 45 | _curry2(function memoizeWith(keyGen, fn) {
|
---|
| 46 | var cache = {};
|
---|
| 47 | return _arity(fn.length, function () {
|
---|
| 48 | var key = keyGen.apply(this, arguments);
|
---|
| 49 |
|
---|
| 50 | if (!_has(key, cache)) {
|
---|
| 51 | cache[key] = fn.apply(this, arguments);
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 54 | return cache[key];
|
---|
| 55 | });
|
---|
| 56 | });
|
---|
| 57 |
|
---|
| 58 | export default memoizeWith; |
---|