n8n/packages/editor-ui/src/composables/useDebounce.ts
OlegIvaniv 9693142985
refactor(editor): Refactor history and debounce mixins to composables (no-changelog) (#5930)
* refactor(editor): Refactor history and debounce mixins to composables and add unit tests (no-changelog)

* Lint fix and use userEvent to fire keydown events

* Fix debounce spec
2023-04-18 11:47:08 +02:00

39 lines
1.1 KiB
TypeScript

import { ref } from 'vue';
import { debounce } from 'lodash-es';
type DebouncedFunction = (...args: unknown[]) => Promise<void> | void;
export function useDebounceHelper() {
// Create a ref for the WeakMap to store debounced functions.
const debouncedFunctions = ref(new WeakMap<DebouncedFunction, DebouncedFunction>());
const callDebounced = async (
func: DebouncedFunction,
options: { debounceTime: number; trailing?: boolean },
...inputParameters: unknown[]
): Promise<void> => {
const { trailing, debounceTime } = options;
// Check if a debounced version of the function is already stored in the WeakMap.
let debouncedFunc = debouncedFunctions.value.get(func);
// If a debounced version is not found, create one and store it in the WeakMap.
if (debouncedFunc === undefined) {
debouncedFunc = debounce(
async (...args: unknown[]) => {
await func(...args);
},
debounceTime,
trailing ? { trailing } : { leading: true },
);
debouncedFunctions.value.set(func, debouncedFunc);
}
await debouncedFunc(...inputParameters);
};
return {
callDebounced,
};
}