mirror of
https://github.com/robonen/tools.git
synced 2026-03-20 10:54:44 +00:00
feat(packages/platform): init new package
This commit is contained in:
47
packages/platform/src/multi/debounce/index.ts
Normal file
47
packages/platform/src/multi/debounce/index.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
export interface DebounceOptions {
|
||||
/**
|
||||
* Call the function on the leading edge of the timeout, instead of waiting for the trailing edge
|
||||
*/
|
||||
readonly immediate?: boolean;
|
||||
|
||||
/**
|
||||
* Call the function on the trailing edge with the last used arguments.
|
||||
* Result of call is from previous call
|
||||
*/
|
||||
readonly trailing?: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_DEBOUNCE_OPTIONS: DebounceOptions = {
|
||||
trailing: true,
|
||||
}
|
||||
|
||||
export function debounce<FnArguments extends unknown[], FnReturn>(
|
||||
fn: (...args: FnArguments) => PromiseLike<FnReturn> | FnReturn,
|
||||
timeout: number = 20,
|
||||
options: DebounceOptions = {},
|
||||
) {
|
||||
options = {
|
||||
...DEFAULT_DEBOUNCE_OPTIONS,
|
||||
...options,
|
||||
};
|
||||
|
||||
if (!Number.isFinite(timeout) || timeout <= 0)
|
||||
throw new TypeError('Debounce timeout must be a positive number');
|
||||
|
||||
// Last result for leading edge
|
||||
let leadingValue: PromiseLike<FnReturn> | FnReturn;
|
||||
|
||||
// Debounce timeout id
|
||||
let timeoutId: NodeJS.Timeout;
|
||||
|
||||
// Promises to be resolved when debounce is finished
|
||||
let resolveList: Array<(value: unknown) => void> = [];
|
||||
|
||||
// State of currently resolving promise
|
||||
let currentResolve: Promise<FnReturn>;
|
||||
|
||||
// Trailing call information
|
||||
let trailingArgs: unknown[];
|
||||
|
||||
|
||||
}
|
||||
15
packages/platform/src/multi/global/index.ts
Normal file
15
packages/platform/src/multi/global/index.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* @name _global
|
||||
* @category Multi
|
||||
* @description Global object that works in any environment
|
||||
*/
|
||||
export const _global =
|
||||
typeof globalThis !== 'undefined'
|
||||
? globalThis
|
||||
: typeof window !== 'undefined'
|
||||
? window
|
||||
: typeof global !== 'undefined'
|
||||
? global
|
||||
: typeof self !== 'undefined'
|
||||
? self
|
||||
: {};
|
||||
2
packages/platform/src/multi/index.ts
Normal file
2
packages/platform/src/multi/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './global';
|
||||
export * from './debounce';
|
||||
Reference in New Issue
Block a user