@todojs/

Proxy 8 - cacheObject()

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
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
var o = cacheObject({
    m: function (x) { return Math.round(Math.random() * x); }
});

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

// Los nuevos métodos, también se les aplica el comportamiento con caché
o.r = function(x) {
    return Math.random() * 1000;
};

console.log('o.r() =', o.r());
console.log('o.r() =', o.r());
console.log('o.r() =', o.r());



function cacheObject(obj) {
    var cacheFunction = new Map();
    // Propiedades ya existentes
    Object.keys(obj).forEach((p) => {
        obj[p] = (typeof obj[p] === 'function' ? cache(obj[p]) : obj[p]);
    });
    // Nuevas propiedades
    return new Proxy(obj, {
        set: (object, property, value) => {
            value = typeof value === 'function' ? cache(value) : value;
            Reflect.set(object, property, value)
        }
    });
}
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