-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathcached.js
60 lines (54 loc) · 1.66 KB
/
cached.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict';
var shouldupdate = require('./shouldupdate');
/**
* Directly fetch `cache` to use outside of Omniscient.
* You can do this if you want to define functions that caches computed
* result to avoid recomputing if invoked with equal arguments as last time.
*
* Returns optimized version of given `f` function for repeated
* calls with an equal inputs. Returned function caches last input
* and a result of the computation for it, which is handy for
* optimizing `render` when computations are run on unchanged parts
* of state. Although note that only last result is cached so it is
* not practical to call it mulitple times with in the same `render`
* call.
*
* @param {Function} Function that does a computation.
*
* @module cached
* @returns {Function} Optimized function
* @api public
*/
module.exports = factory();
/**
* Create a “local” instance of the `cache` with overriden defaults.
*
* ### Options
* ```js
* {
* isEqualProps: function (currentProps, nextProps), // check props
* }
* ```
*
* @param {Object} [Options] Options with defaults to override
*
* @module cached.withDefaults
* @returns {Function} cached with overriden defaults
* @api public
*/
module.exports.withDefaults = factory;
function factory(methods) {
var isEqual = (methods && methods.isEqualProps) || shouldupdate.isEqualProps;
return function cached(f) {
var input, output;
return function() {
if (!isEqual(arguments, input)) {
output = f.apply(this, arguments);
}
// Update input either way to allow GC reclaim it unless
// anything else is referring to it.
input = arguments;
return output;
};
};
}