|
| 1 | +// function calc(x) { |
| 2 | +// // Complexity |
| 3 | +// console.log(`Calc with ${x}`); |
| 4 | +// return x; |
| 5 | +// } |
| 6 | + |
| 7 | +// function cachingDecorator(func) { |
| 8 | +// const cache = new Map(); |
| 9 | + |
| 10 | +// return function(x) { |
| 11 | +// if (cache.has(x)) { |
| 12 | +// return cache.get(x); |
| 13 | +// } |
| 14 | + |
| 15 | +// const result = func(x); |
| 16 | +// cache.set(x, result); |
| 17 | + |
| 18 | +// return result; |
| 19 | +// }; |
| 20 | +// } |
| 21 | + |
| 22 | +// calc = cachingDecorator(calc); |
| 23 | + |
| 24 | +// console.log(calc(1)); |
| 25 | + |
| 26 | +// console.log(calc(1)); |
| 27 | + |
| 28 | +// console.log(calc(2)); |
| 29 | + |
| 30 | +// console.log(calc(2)); |
| 31 | +// console.log(calc(2)); |
| 32 | + |
| 33 | +// const worker = { |
| 34 | +// multiplier: 2, |
| 35 | +// calc: function(x) { |
| 36 | +// console.log(`Calc with ${x}`); |
| 37 | +// return x * this.multiplier; |
| 38 | +// } |
| 39 | +// }; |
| 40 | + |
| 41 | +// function cachingDecorator(func) { |
| 42 | +// const cache = new Map(); |
| 43 | + |
| 44 | +// return function(x) { |
| 45 | +// if (cache.has(x)) { |
| 46 | +// return cache.get(x); |
| 47 | +// } |
| 48 | + |
| 49 | +// const result = func.call(this, x); |
| 50 | +// cache.set(x, result); |
| 51 | + |
| 52 | +// return result; |
| 53 | +// }; |
| 54 | +// } |
| 55 | + |
| 56 | +// worker.calc = cachingDecorator(worker.calc); |
| 57 | + |
| 58 | +// console.log(worker.calc(10)); |
| 59 | +// console.log(worker.calc(10)); |
| 60 | + |
| 61 | +// const numbers = [4, 5, 6, 7, 8, 9, 2, 3, 0, 1]; |
| 62 | +// const max = Math.max.apply(null, numbers); |
| 63 | +// const min = Math.min.apply(null, numbers); |
| 64 | + |
| 65 | +// console.log(max, min); |
| 66 | + |
| 67 | +const worker = { |
| 68 | + calc(min, max) { |
| 69 | + console.log(`Calc with ${min}, and ${max}`); |
| 70 | + return min + max; |
| 71 | + } |
| 72 | +}; |
| 73 | + |
| 74 | +function cachingDecorator(func, hash) { |
| 75 | + let cache = new Map(); |
| 76 | + |
| 77 | + return function(...args) { |
| 78 | + let key = hash(args); |
| 79 | + if (cache.has(key)) { |
| 80 | + return cache.get(key); |
| 81 | + } |
| 82 | + |
| 83 | + let result = func.apply(this, args); |
| 84 | + cache.set(key, result); |
| 85 | + |
| 86 | + return result; |
| 87 | + }; |
| 88 | +} |
| 89 | + |
| 90 | +function hash(...args) { |
| 91 | + return args.join(); |
| 92 | +} |
| 93 | + |
| 94 | +worker.calc = cachingDecorator(worker.calc, hash); |
| 95 | +console.log(worker.calc(1, 2)); |
| 96 | + |
| 97 | +console.log(worker.calc(1, 2)); |
0 commit comments