Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/git-base/src/decorators.ts
3316 views
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 function (original: any, context: ClassMethodDecoratorContext) {
52
if (context.kind !== 'method') {
53
throw new Error('not supported');
54
}
55
return decorator(original, context.name.toString());
56
};
57
}
58
59