|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | + * Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | + *--------------------------------------------------------------------------------------------*/ |
| 5 | + |
| 6 | +import { done } from './util'; |
| 7 | + |
| 8 | +export function debounce(delay: number): Function { |
| 9 | + return decorate((fn, key) => { |
| 10 | + const timerKey = `$debounce$${key}`; |
| 11 | + |
| 12 | + return function (this: any, ...args: any[]) { |
| 13 | + clearTimeout(this[timerKey]); |
| 14 | + this[timerKey] = setTimeout(() => fn.apply(this, args), delay); |
| 15 | + }; |
| 16 | + }); |
| 17 | +} |
| 18 | + |
| 19 | +export const throttle = decorate(_throttle); |
| 20 | + |
| 21 | +function _throttle<T>(fn: Function, key: string): Function { |
| 22 | + const currentKey = `$throttle$current$${key}`; |
| 23 | + const nextKey = `$throttle$next$${key}`; |
| 24 | + |
| 25 | + const trigger = function (this: any, ...args: any[]) { |
| 26 | + if (this[nextKey]) { |
| 27 | + return this[nextKey]; |
| 28 | + } |
| 29 | + |
| 30 | + if (this[currentKey]) { |
| 31 | + this[nextKey] = done(this[currentKey]).then(() => { |
| 32 | + this[nextKey] = undefined; |
| 33 | + return trigger.apply(this, args); |
| 34 | + }); |
| 35 | + |
| 36 | + return this[nextKey]; |
| 37 | + } |
| 38 | + |
| 39 | + this[currentKey] = fn.apply(this, args) as Promise<T>; |
| 40 | + |
| 41 | + const clear = () => this[currentKey] = undefined; |
| 42 | + done(this[currentKey]).then(clear, clear); |
| 43 | + |
| 44 | + return this[currentKey]; |
| 45 | + }; |
| 46 | + |
| 47 | + return trigger; |
| 48 | +} |
| 49 | + |
| 50 | +function decorate(decorator: (fn: Function, key: string) => Function): Function { |
| 51 | + return (_target: any, key: string, descriptor: any) => { |
| 52 | + let fnKey: string | null = null; |
| 53 | + let fn: Function | null = null; |
| 54 | + |
| 55 | + if (typeof descriptor.value === 'function') { |
| 56 | + fnKey = 'value'; |
| 57 | + fn = descriptor.value; |
| 58 | + } else if (typeof descriptor.get === 'function') { |
| 59 | + fnKey = 'get'; |
| 60 | + fn = descriptor.get; |
| 61 | + } |
| 62 | + |
| 63 | + if (!fn || !fnKey) { |
| 64 | + throw new Error('not supported'); |
| 65 | + } |
| 66 | + |
| 67 | + descriptor[fnKey] = decorator(fn, key); |
| 68 | + }; |
| 69 | +} |
0 commit comments