-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
memoizeWith.js
43 lines (41 loc) · 1.29 KB
/
memoizeWith.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import _arity from './internal/_arity';
import _curry2 from './internal/_curry2';
import _has from './internal/_has';
/**
* Takes an additional function that will be applied to a given argument set
* and used to create the cache key under which the results of the function to be
* memoized will be stored. Care must be taken when implementing key generation
* to avoid clashes that may overwrite previous entries erroneously.
*
*
* @func
* @memberOf R
* @since v0.24.0
* @category Function
* @sig (*... -> String) -> (*... -> a) -> (*... -> a)
* @param {Function} fn The function to generate the cache key.
* @param {Function} fn The function to memoize.
* @return {Function} Memoized version of `fn`.
* @example
*
* let count = 0;
* const factorial = R.memoizeWith(R.identity, n => {
* count += 1;
* return R.product(R.range(1, n + 1));
* });
* factorial(5); //=> 120
* factorial(5); //=> 120
* factorial(5); //=> 120
* count; //=> 1
*/
var memoizeWith = _curry2(function memoizeWith(mFn, fn) {
var cache = {};
return _arity(fn.length, function() {
var key = mFn.apply(this, arguments);
if (!_has(key, cache)) {
cache[key] = fn.apply(this, arguments);
}
return cache[key];
});
});
export default memoizeWith;