add Function.js, some updates in OxJS
This commit is contained in:
parent
80f9a1a33d
commit
1db649bd61
6 changed files with 123 additions and 90 deletions
29
source/Ox/js/Function.js
Normal file
29
source/Ox/js/Function.js
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
/*@
|
||||
Ox.cache <f> Memoize a function
|
||||
<script>
|
||||
var f = Ox.cache(function(n) { return n * Math.random(); });
|
||||
</script>
|
||||
> f(10) == f(10);
|
||||
true
|
||||
> f(10) == f.clear()(10);
|
||||
false
|
||||
@*/
|
||||
Ox.cache = function(fn) {
|
||||
var cache = {},
|
||||
ret = function() {
|
||||
var key = JSON.stringify(Ox.makeArray(arguments));
|
||||
return key in cache ? cache[key]
|
||||
: (cache[key] = fn.apply(this, arguments));
|
||||
};
|
||||
ret.clear = function() {
|
||||
if (arguments.length == 0) {
|
||||
cache = {};
|
||||
} else {
|
||||
Ox.toArray(arguments).forEach(function(key) {
|
||||
delete cache[key];
|
||||
});
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue