diff --git a/docs/daily/2019-11-25.md b/docs/daily/2019-11-25.md new file mode 100644 index 0000000..7b64169 --- /dev/null +++ b/docs/daily/2019-11-25.md @@ -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的装饰器 + + diff --git a/docs/daily/README.md b/docs/daily/README.md index cf1160e..87006e4 100644 --- a/docs/daily/README.md +++ b/docs/daily/README.md @@ -25,6 +25,12 @@ ### 历史汇总 +#### [写一个debounce的装饰器](./2019-11-25.md) + +tag: `编程题` + +时间: 2019-11-25 + #### [以下关于Javascript执行引擎描述正确的是](./2019-09-24.md) tag:`阿里前端校招笔试` diff --git "a/docs/daily/assets/2019-11-25 - \345\206\231\344\270\200\344\270\252debounce\347\232\204\350\243\205\351\245\260\345\231\250-unit-test.png" "b/docs/daily/assets/2019-11-25 - \345\206\231\344\270\200\344\270\252debounce\347\232\204\350\243\205\351\245\260\345\231\250-unit-test.png" new file mode 100644 index 0000000..ba7e1a7 Binary files /dev/null and "b/docs/daily/assets/2019-11-25 - \345\206\231\344\270\200\344\270\252debounce\347\232\204\350\243\205\351\245\260\345\231\250-unit-test.png" differ