Skip to content

Commit

Permalink
feat: 2019-11-25 - 写一个debounce的装饰器 (#69)
Browse files Browse the repository at this point in the history
2019-11-25 - 写一个debounce的装饰器
  • Loading branch information
azl397985856 committed Nov 26, 2019
2 parents 9b84ce3 + 26f1a0a commit 8852db4
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 0 deletions.
94 changes: 94 additions & 0 deletions docs/daily/2019-11-25.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# 每日一题 - 2019-11-25 - 写一个debounce的装饰器

### 信息卡片

- 时间:2019-11-25
- tag:`编程题`

### 问题描述
实现一个debounce装饰器

### 参考实现

##### 代码实现
```typescript
/**
* 装饰器的debounce
* @param delay
*/
export function debounce(delay: number): Function {
return (
target: Function,
propertyKey: string,
propertyDesciptor: PropertyDescriptor
) => {
const method = propertyDesciptor.value;
let timer = null;
propertyDesciptor.value = (...args) => {
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => method(...args), delay);
};
return propertyDesciptor;
};
}
```

##### 单元测试

``` typescript
import { debounce } from './index';

jest.useFakeTimers();

let a: any;
let mockFunc: jest.Mock;
beforeEach(() => {
mockFunc = jest.fn();
class Test {
@debounce(1000)
sayHi() {
mockFunc();
}
}
a = new Test();
});

describe('debounce:', () => {
test('debounced function should be called after the delay time', () => {
a.sayHi();
expect(mockFunc).toHaveBeenCalledTimes(0);
jest.advanceTimersByTime(1000);
expect(mockFunc).toHaveBeenCalledTimes(1);
});

test('debounced function should not be called before the delay time', () => {
a.sayHi();
expect(mockFunc).toHaveBeenCalledTimes(0);
let count = 100;
while (count--) {
a.sayHi();
}
expect(mockFunc).toHaveBeenCalledTimes(0);

count = 100;
while (count--) {
jest.advanceTimersByTime(999);
a.sayHi();
}
expect(mockFunc).toHaveBeenCalledTimes(0);
});
});
```

执行结果
![](assets/2019-11-25 - 写一个debounce的装饰器-unit-test.png)


### 扩展

- 写一个throttle的装饰器


6 changes: 6 additions & 0 deletions docs/daily/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@

### 历史汇总

#### [写一个debounce的装饰器](./2019-11-25.md)

tag: `编程题`

时间: 2019-11-25

#### [以下关于Javascript执行引擎描述正确的是](./2019-09-24.md)

tag:`阿里前端校招笔试`
Expand Down
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 8852db4

Please sign in to comment.