forked from MrTreasure/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
94 lines (80 loc) · 1.82 KB
/
index.ts
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
const debounce = (dealy: number, fun: Function): Function => {
let timer = null
return function (...args) {
if (timer) {
global.clearTimeout(timer)
timer = null
}
timer = global.setTimeout(() => {
fun.apply(null, args)
}, dealy)
}
}
const throttle = (dealy: number, fun: Function): Function => {
let timer = null
return function (...args) {
if (timer) return
timer = global.setTimeout(() => {
fun.apply(null, args)
timer = null
}, dealy)
}
}
const decoratorDebounce = (dealy: number) => {
return (target, propertyKey, descriptor) => {
let timer = null
let method = descriptor.value
descriptor.value = function (...args) {
if (timer) {
// console.log(timer)
global.clearTimeout(timer)
} else {
console.log('here')
timer = global.setTimeout(() => {
console.log('excute')
method.apply(target, args)
}, dealy)
}
}
}
}
const decoratorThrottle = (dealy: number) => {
let timer = null
return (target, propertyKey, descriptor) => {
let method = descriptor.value
descriptor.value = function (...args) {
if (timer) {
return
} else {
timer = global.setTimeout(() => {
return method.apply(target, args)
}, dealy)
}
}
}
}
// test
function log (str: string | number) {
console.log(str)
}
// const debounceLog = debounce(2000, log)
// const throttleLog = throttle(1, log)
// debounceLog(1)
// debounceLog(2)
// debounceLog(3)
class Test {
map: Map<string | number, number | string >
constructor () {
// this.map = new Map()
// this.map.set(1, 2)
// this.map.set(2, '4')
}
@decoratorDebounce(1000)
say (str) {
console.log(str)
}
}
const test1 = new Test()
test1.say(1)
test1.say(2)
test1.say(3)