@todojs/

Proxy 7 - cache()

JavaScript

No description

fork
loading
main.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
var m = cache(function (x) { return Math.round(Math.random() * x); });

console.log('m(10) =', m(10));
console.log('m(10) =', m(10));
console.log('m(10) =', m(10));
console.log('m(20) =', m(20));
console.log('m(20) =', m(20));
console.log('m(20) =', m(20));
console.log('m(100) =', m(30));
console.log('m(100) =', m(30));
console.log('m(100) =', m(30));

function cache(fn) {
    var cacheData = new Map();
    fn = new Proxy(fn, {
        apply: function(target, thisArg, argumentsList) {
            var args = argumentsList.toString();
            if (cacheData.has(args)) {
                return cacheData.get(args);
            }
            var ret = Reflect.apply(target, thisArg, argumentsList);
            cacheData.set(args, ret);
            return ret;
        }
    });
    fn.clearCache = () => !cacheData.clear();
    return fn;
}
Native Browser JavaScript