-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcachingDecorator.js
More file actions
94 lines (79 loc) · 1.75 KB
/
cachingDecorator.js
File metadata and controls
94 lines (79 loc) · 1.75 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
function cachingDecorator(func, hash) {
let cache = new Map();
return function () {
let key = hash(arguments);
if (cache.has(key)) {
return cache.get(key);
}
let result = func.call(this, ...arguments);
cache.set(key, result);
return result;
};
}
function hash(args) {
return [].join.call(args);
}
function spy(func) {
function wrapper(...args) {
wrapper.calls.push(args)
return func.apply(this, arguments)
}
wrapper.calls = []
return wrapper
}
function work(a, b) {
console.log(a + b)
}
work = spy(work)
work(1, 6)
work(1, 2)
work(6, 4)
for (let args of work.calls) {
console.log('call:' + args.join())
}
function delay(f, ms) {
return function () {
setTimeout(() => f.apply(this, arguments), ms)
}
}
function f(x) {
console.log(x)
}
let f1000 = delay(f, 1000)
let f2000 = delay(f, 2000)
f1000('test')
f2000('test')
function debounce(f, ms) {
let isCooldown = false
return function () {
if (isCooldown) return;
f.apply(this, arguments)
isCooldown = true
setTimeout(() => isCooldown = false, ms)
}
}
let deb = debounce(console.log, 5000)
deb(2)
deb(7)
function throttle(func, ms) {
let isThrottled = false
savedArgs,
savedThis;
function wrapper() {
if (isThrottled) {
savedArgs = arguments
savedThis = this
return
}
func.apply(this, arguments)
isThrottled = true
setTimeout(function () {
isThrottled = false
if (savedArgs) {
wrapper.apply(savedThis, savedArgs)
savedArgs = savedThis = null
}
}, ms)
}
return wrapper
}