Skip to content

Commit 0dd7e06

Browse files
committed
refactor: use most generic version to build simpler versions
1 parent db1f8d9 commit 0dd7e06

File tree

2 files changed

+21
-24
lines changed

2 files changed

+21
-24
lines changed

packages/core/src/shared/utilities/functionUtils.ts

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -90,36 +90,19 @@ export function debounce<Input extends any[], Output>(
9090
cb: (...args: Input) => Output | Promise<Output>,
9191
delay: number = 0
9292
): (...args: Input) => Promise<Output> {
93-
let timeout: Timeout | undefined
94-
let promise: Promise<Output> | undefined
95-
96-
return (...args: Input) => {
97-
timeout?.refresh()
98-
99-
return (promise ??= new Promise<Output>((resolve, reject) => {
100-
timeout = new Timeout(delay)
101-
timeout.onCompletion(async () => {
102-
timeout = promise = undefined
103-
try {
104-
resolve(await cb(...args))
105-
} catch (err) {
106-
reject(err)
107-
}
108-
})
109-
}))
110-
}
93+
return cancellableDebounce(cb, delay).promise
11194
}
11295

11396
/**
11497
*
11598
* Similar to {@link debounce}, but allows the function to be cancelled and allow callbacks to pass function parameters.
11699
*/
117-
export function cancellableDebounce<T, U extends any[]>(
118-
cb: (...args: U) => T | Promise<T>,
100+
export function cancellableDebounce<Input extends any[], Output>(
101+
cb: (...args: Input) => Output | Promise<Output>,
119102
delay: number = 0
120-
): { promise: (...args: U) => Promise<T>; cancel: () => void } {
103+
): { promise: (...args: Input) => Promise<Output>; cancel: () => void } {
121104
let timeout: Timeout | undefined
122-
let promise: Promise<T> | undefined
105+
let promise: Promise<Output> | undefined
123106

124107
const cancel = (): void => {
125108
if (timeout) {
@@ -130,7 +113,21 @@ export function cancellableDebounce<T, U extends any[]>(
130113
}
131114

132115
return {
133-
promise: debounce(cb, delay),
116+
promise: (...args: Input) => {
117+
timeout?.refresh()
118+
119+
return (promise ??= new Promise<Output>((resolve, reject) => {
120+
timeout = new Timeout(delay)
121+
timeout.onCompletion(async () => {
122+
timeout = promise = undefined
123+
try {
124+
resolve(await cb(...args))
125+
} catch (err) {
126+
reject(err)
127+
}
128+
})
129+
}))
130+
},
134131
cancel: cancel,
135132
}
136133
}

packages/core/src/test/shared/utilities/functionUtils.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ describe('functionUtils', function () {
5252

5353
describe('debounce', function () {
5454
let counter: number
55-
let fn: () => Promise<unknown> | unknown
55+
let fn: () => Promise<unknown>
5656

5757
beforeEach(function () {
5858
counter = 0

0 commit comments

Comments
 (0)