Skip to content

Commit 8852db4

Browse files
authored
feat: 2019-11-25 - 写一个debounce的装饰器 (azl397985856#69)
2019-11-25 - 写一个debounce的装饰器
2 parents 9b84ce3 + 26f1a0a commit 8852db4

File tree

3 files changed

+100
-0
lines changed

3 files changed

+100
-0
lines changed

docs/daily/2019-11-25.md

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# 每日一题 - 2019-11-25 - 写一个debounce的装饰器
2+
3+
### 信息卡片
4+
5+
- 时间:2019-11-25
6+
- tag:`编程题`
7+
8+
### 问题描述
9+
实现一个debounce装饰器
10+
11+
### 参考实现
12+
13+
##### 代码实现
14+
```typescript
15+
/**
16+
* 装饰器的debounce
17+
* @param delay
18+
*/
19+
export function debounce(delay: number): Function {
20+
return (
21+
target: Function,
22+
propertyKey: string,
23+
propertyDesciptor: PropertyDescriptor
24+
) => {
25+
const method = propertyDesciptor.value;
26+
let timer = null;
27+
propertyDesciptor.value = (...args) => {
28+
if (timer) {
29+
clearTimeout(timer);
30+
timer = null;
31+
}
32+
timer = setTimeout(() => method(...args), delay);
33+
};
34+
return propertyDesciptor;
35+
};
36+
}
37+
```
38+
39+
##### 单元测试
40+
41+
``` typescript
42+
import { debounce } from './index';
43+
44+
jest.useFakeTimers();
45+
46+
let a: any;
47+
let mockFunc: jest.Mock;
48+
beforeEach(() => {
49+
mockFunc = jest.fn();
50+
class Test {
51+
@debounce(1000)
52+
sayHi() {
53+
mockFunc();
54+
}
55+
}
56+
a = new Test();
57+
});
58+
59+
describe('debounce:', () => {
60+
test('debounced function should be called after the delay time', () => {
61+
a.sayHi();
62+
expect(mockFunc).toHaveBeenCalledTimes(0);
63+
jest.advanceTimersByTime(1000);
64+
expect(mockFunc).toHaveBeenCalledTimes(1);
65+
});
66+
67+
test('debounced function should not be called before the delay time', () => {
68+
a.sayHi();
69+
expect(mockFunc).toHaveBeenCalledTimes(0);
70+
let count = 100;
71+
while (count--) {
72+
a.sayHi();
73+
}
74+
expect(mockFunc).toHaveBeenCalledTimes(0);
75+
76+
count = 100;
77+
while (count--) {
78+
jest.advanceTimersByTime(999);
79+
a.sayHi();
80+
}
81+
expect(mockFunc).toHaveBeenCalledTimes(0);
82+
});
83+
});
84+
```
85+
86+
执行结果
87+
![](assets/2019-11-25 - 写一个debounce的装饰器-unit-test.png)
88+
89+
90+
### 扩展
91+
92+
- 写一个throttle的装饰器
93+
94+

docs/daily/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@
2525

2626
### 历史汇总
2727

28+
#### [写一个debounce的装饰器](./2019-11-25.md)
29+
30+
tag: `编程题`
31+
32+
时间: 2019-11-25
33+
2834
#### [以下关于Javascript执行引擎描述正确的是](./2019-09-24.md)
2935

3036
tag:`阿里前端校招笔试`
92.4 KB
Loading

0 commit comments

Comments
 (0)