-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_closure_4.js
43 lines (32 loc) · 911 Bytes
/
js_closure_4.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
const engine = {
predefined() {
return [1];
},
createNewValues(...values) {
console.log(`called including ${values}`);
const prevValues = this.predefined();
const newValues = values.concat(prevValues);
return newValues;
}
};
function cachingDecorator(callback) {
const cache = new Map();
function random(...values) {
const key = values.join('');
if (cache.has(key)) {
const value = cache.get(key);
return value;
}
const result = callback.apply(this, values); // "this" is passed correctly now
cache.set(key, result);
return result;
}
return random;
}
function Usecase() {
engine.createNewValues = cachingDecorator(engine.createNewValues); // now make it cached
console.log(engine.createNewValues(2)); // do calculate
console.log(engine.createNewValues(2, 3)); // do calculate
console.log(engine.createNewValues(2, 3)); // don't calculate (cached)
}
Usecase();