source: node_modules/ramda/es/memoizeWith.js

main
Last change on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 2.0 KB
RevLine 
[d24f17c]1import _arity from "./internal/_arity.js";
2import _curry2 from "./internal/_curry2.js";
3import _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
43var 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
58export default memoizeWith;
Note: See TracBrowser for help on using the repository browser.