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