@tanstack/pacer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/async-debouncer.cjs +109 -0
  3. package/dist/cjs/async-debouncer.cjs.map +1 -0
  4. package/dist/cjs/async-debouncer.d.cts +99 -0
  5. package/dist/cjs/async-queuer.cjs +293 -0
  6. package/dist/cjs/async-queuer.cjs.map +1 -0
  7. package/dist/cjs/async-queuer.d.cts +197 -0
  8. package/dist/cjs/async-rate-limiter.cjs +122 -0
  9. package/dist/cjs/async-rate-limiter.cjs.map +1 -0
  10. package/dist/cjs/async-rate-limiter.d.cts +132 -0
  11. package/dist/cjs/async-throttler.cjs +115 -0
  12. package/dist/cjs/async-throttler.cjs.map +1 -0
  13. package/dist/cjs/async-throttler.d.cts +93 -0
  14. package/dist/cjs/compare.cjs +72 -0
  15. package/dist/cjs/compare.cjs.map +1 -0
  16. package/dist/cjs/compare.d.cts +12 -0
  17. package/dist/cjs/debouncer.cjs +74 -0
  18. package/dist/cjs/debouncer.cjs.map +1 -0
  19. package/dist/cjs/debouncer.d.cts +96 -0
  20. package/dist/cjs/index.cjs +32 -0
  21. package/dist/cjs/index.cjs.map +1 -0
  22. package/dist/cjs/index.d.cts +9 -0
  23. package/dist/cjs/queuer.cjs +231 -0
  24. package/dist/cjs/queuer.cjs.map +1 -0
  25. package/dist/cjs/queuer.d.cts +221 -0
  26. package/dist/cjs/rate-limiter.cjs +115 -0
  27. package/dist/cjs/rate-limiter.cjs.map +1 -0
  28. package/dist/cjs/rate-limiter.d.cts +147 -0
  29. package/dist/cjs/throttler.cjs +120 -0
  30. package/dist/cjs/throttler.cjs.map +1 -0
  31. package/dist/cjs/throttler.d.cts +139 -0
  32. package/dist/esm/async-debouncer.d.ts +99 -0
  33. package/dist/esm/async-debouncer.js +109 -0
  34. package/dist/esm/async-debouncer.js.map +1 -0
  35. package/dist/esm/async-queuer.d.ts +197 -0
  36. package/dist/esm/async-queuer.js +293 -0
  37. package/dist/esm/async-queuer.js.map +1 -0
  38. package/dist/esm/async-rate-limiter.d.ts +132 -0
  39. package/dist/esm/async-rate-limiter.js +122 -0
  40. package/dist/esm/async-rate-limiter.js.map +1 -0
  41. package/dist/esm/async-throttler.d.ts +93 -0
  42. package/dist/esm/async-throttler.js +115 -0
  43. package/dist/esm/async-throttler.js.map +1 -0
  44. package/dist/esm/compare.d.ts +12 -0
  45. package/dist/esm/compare.js +72 -0
  46. package/dist/esm/compare.js.map +1 -0
  47. package/dist/esm/debouncer.d.ts +96 -0
  48. package/dist/esm/debouncer.js +74 -0
  49. package/dist/esm/debouncer.js.map +1 -0
  50. package/dist/esm/index.d.ts +9 -0
  51. package/dist/esm/index.js +32 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/queuer.d.ts +221 -0
  54. package/dist/esm/queuer.js +231 -0
  55. package/dist/esm/queuer.js.map +1 -0
  56. package/dist/esm/rate-limiter.d.ts +147 -0
  57. package/dist/esm/rate-limiter.js +115 -0
  58. package/dist/esm/rate-limiter.js.map +1 -0
  59. package/dist/esm/throttler.d.ts +139 -0
  60. package/dist/esm/throttler.js +120 -0
  61. package/dist/esm/throttler.js.map +1 -0
  62. package/package.json +150 -0
  63. package/src/async-debouncer.ts +197 -0
  64. package/src/async-queuer.ts +447 -0
  65. package/src/async-rate-limiter.ts +228 -0
  66. package/src/async-throttler.ts +194 -0
  67. package/src/compare.ts +105 -0
  68. package/src/debouncer.ts +164 -0
  69. package/src/index.ts +9 -0
  70. package/src/queuer.ts +394 -0
  71. package/src/rate-limiter.ts +236 -0
  72. package/src/throttler.ts +222 -0
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Options for configuring an async throttled function
3
+ */
4
+ export interface AsyncThrottlerOptions {
5
+ /**
6
+ * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
7
+ * Defaults to true.
8
+ */
9
+ enabled?: boolean;
10
+ /**
11
+ * Time window in milliseconds during which the function can only be executed once
12
+ * Defaults to 0ms
13
+ */
14
+ wait: number;
15
+ /**
16
+ * Optional error handler for when the throttled function throws
17
+ */
18
+ onError?: (error: unknown) => void;
19
+ }
20
+ /**
21
+ * A class that creates an async throttled function.
22
+ *
23
+ * Throttling limits how often a function can be executed, allowing only one execution within a specified time window.
24
+ * Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
25
+ * regular interval regardless of how often it's called.
26
+ *
27
+ * This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to
28
+ * ensure a maximum execution frequency.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * const throttler = new AsyncThrottler(async (value: string) => {
33
+ * await saveToAPI(value);
34
+ * }, { wait: 1000 });
35
+ *
36
+ * // Will only execute once per second no matter how often called
37
+ * inputElement.addEventListener('input', () => {
38
+ * throttler.maybeExecute(inputElement.value);
39
+ * });
40
+ * ```
41
+ */
42
+ export declare class AsyncThrottler<TFn extends (...args: Array<any>) => Promise<any>, TArgs extends Parameters<TFn>> {
43
+ private fn;
44
+ private abortController;
45
+ private executionCount;
46
+ private isExecuting;
47
+ private isScheduled;
48
+ private lastArgs;
49
+ private nextExecutionTime;
50
+ private options;
51
+ constructor(fn: TFn, initialOptions: AsyncThrottlerOptions);
52
+ /**
53
+ * Updates the throttler options
54
+ * Returns the new options state
55
+ */
56
+ setOptions(newOptions: Partial<AsyncThrottlerOptions>): Required<AsyncThrottlerOptions>;
57
+ /**
58
+ * Returns the number of times the function has been executed
59
+ */
60
+ getExecutionCount(): number;
61
+ /**
62
+ * Returns the next execution time
63
+ */
64
+ getNextExecutionTime(): number;
65
+ /**
66
+ * Cancels any pending execution
67
+ */
68
+ cancel(): void;
69
+ /**
70
+ * Attempts to execute the throttled function
71
+ * If a call is already in progress, it may be blocked or queued depending on the `wait` option
72
+ */
73
+ maybeExecute(...args: TArgs): Promise<void>;
74
+ private delay;
75
+ private executeFunction;
76
+ }
77
+ /**
78
+ * Creates an async throttled function that limits how often the function can execute.
79
+ * The throttled function will execute at most once per wait period, even if called multiple times.
80
+ * If called while executing, it will wait until execution completes before scheduling the next call.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * const throttled = asyncThrottle(async () => {
85
+ * await someAsyncOperation();
86
+ * }, { wait: 1000 });
87
+ *
88
+ * // This will execute at most once per second
89
+ * await throttled();
90
+ * await throttled(); // Waits 1 second before executing
91
+ * ```
92
+ */
93
+ export declare function asyncThrottle<TFn extends (...args: Array<any>) => Promise<any>>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions, 'enabled'>): (...args: Parameters<TFn>) => Promise<void>;
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ function replaceEqualDeep(a, b) {
4
+ if (a === b) {
5
+ return a;
6
+ }
7
+ const array = isPlainArray(a) && isPlainArray(b);
8
+ if (array || isPlainObject(a) && isPlainObject(b)) {
9
+ const aItems = array ? a : Object.keys(a);
10
+ const aSize = aItems.length;
11
+ const bItems = array ? b : Object.keys(b);
12
+ const bSize = bItems.length;
13
+ const copy = array ? [] : {};
14
+ let equalItems = 0;
15
+ for (let i = 0; i < bSize; i++) {
16
+ const key = array ? i : bItems[i];
17
+ if ((!array && aItems.includes(key) || array) && a[key] === void 0 && b[key] === void 0) {
18
+ copy[key] = void 0;
19
+ equalItems++;
20
+ } else {
21
+ copy[key] = replaceEqualDeep(a[key], b[key]);
22
+ if (copy[key] === a[key] && a[key] !== void 0) {
23
+ equalItems++;
24
+ }
25
+ }
26
+ }
27
+ return aSize === bSize && equalItems === aSize ? a : copy;
28
+ }
29
+ return b;
30
+ }
31
+ function shallowEqualObjects(a, b) {
32
+ if (!b || Object.keys(a).length !== Object.keys(b).length) {
33
+ return false;
34
+ }
35
+ for (const key in a) {
36
+ if (a[key] !== b[key]) {
37
+ return false;
38
+ }
39
+ }
40
+ return true;
41
+ }
42
+ function isPlainArray(value) {
43
+ return Array.isArray(value) && value.length === Object.keys(value).length;
44
+ }
45
+ function isPlainObject(o) {
46
+ if (!hasObjectPrototype(o)) {
47
+ return false;
48
+ }
49
+ const ctor = o.constructor;
50
+ if (ctor === void 0) {
51
+ return true;
52
+ }
53
+ const prot = ctor.prototype;
54
+ if (!hasObjectPrototype(prot)) {
55
+ return false;
56
+ }
57
+ if (!prot.hasOwnProperty("isPrototypeOf")) {
58
+ return false;
59
+ }
60
+ if (Object.getPrototypeOf(o) !== Object.prototype) {
61
+ return false;
62
+ }
63
+ return true;
64
+ }
65
+ function hasObjectPrototype(o) {
66
+ return Object.prototype.toString.call(o) === "[object Object]";
67
+ }
68
+ exports.isPlainArray = isPlainArray;
69
+ exports.isPlainObject = isPlainObject;
70
+ exports.replaceEqualDeep = replaceEqualDeep;
71
+ exports.shallowEqualObjects = shallowEqualObjects;
72
+ //# sourceMappingURL=compare.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compare.cjs","sources":["../../src/compare.ts"],"sourcesContent":["/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T): T\nexport function replaceEqualDeep(a: any, b: any): any {\n if (a === b) {\n return a\n }\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (array || (isPlainObject(a) && isPlainObject(b))) {\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i]\n if (\n ((!array && aItems.includes(key)) || array) &&\n a[key] === undefined &&\n b[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(a[key], b[key])\n if (copy[key] === a[key] && a[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n }\n\n return b\n}\n\n/**\n * Shallow compare objects.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\nexport function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\n// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types\nexport function isPlainObject(o: any): o is Object {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const ctor = o.constructor\n if (ctor === undefined) {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n"],"names":[],"mappings":";;AAMgB,SAAA,iBAAiB,GAAQ,GAAa;AACpD,MAAI,MAAM,GAAG;AACJ,WAAA;AAAA,EAAA;AAGT,QAAM,QAAQ,aAAa,CAAC,KAAK,aAAa,CAAC;AAE/C,MAAI,SAAU,cAAc,CAAC,KAAK,cAAc,CAAC,GAAI;AACnD,UAAM,SAAS,QAAQ,IAAI,OAAO,KAAK,CAAC;AACxC,UAAM,QAAQ,OAAO;AACrB,UAAM,SAAS,QAAQ,IAAI,OAAO,KAAK,CAAC;AACxC,UAAM,QAAQ,OAAO;AACrB,UAAM,OAAY,QAAQ,CAAA,IAAK,CAAC;AAEhC,QAAI,aAAa;AAEjB,aAAS,IAAI,GAAG,IAAI,OAAO,KAAK;AAC9B,YAAM,MAAM,QAAQ,IAAI,OAAO,CAAC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C,MAAM;AAC/C;;;;;"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * This function returns `a` if `b` is deeply equal.
3
+ * If not, it will replace any deeply equal children of `b` with those of `a`.
4
+ * This can be used for structural sharing between JSON values for example.
5
+ */
6
+ export declare function replaceEqualDeep<T>(a: unknown, b: T): T;
7
+ /**
8
+ * Shallow compare objects.
9
+ */
10
+ export declare function shallowEqualObjects<T extends Record<string, any>>(a: T, b: T | undefined): boolean;
11
+ export declare function isPlainArray(value: unknown): boolean;
12
+ export declare function isPlainObject(o: any): o is Object;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const defaultOptions = {
4
+ enabled: true,
5
+ leading: false,
6
+ trailing: true,
7
+ wait: 0
8
+ };
9
+ class Debouncer {
10
+ constructor(fn, initialOptions) {
11
+ this.fn = fn;
12
+ this.canLeadingExecute = true;
13
+ this.executionCount = 0;
14
+ this.options = {
15
+ ...defaultOptions,
16
+ ...initialOptions
17
+ };
18
+ }
19
+ /**
20
+ * Updates the debouncer options
21
+ * Returns the new options state
22
+ */
23
+ setOptions(newOptions) {
24
+ this.options = {
25
+ ...this.options,
26
+ ...newOptions
27
+ };
28
+ return this.options;
29
+ }
30
+ /**
31
+ * Returns the number of times the function has been executed
32
+ */
33
+ getExecutionCount() {
34
+ return this.executionCount;
35
+ }
36
+ /**
37
+ * Attempts to execute the debounced function
38
+ * If a call is already in progress, it will be queued
39
+ */
40
+ maybeExecute(...args) {
41
+ if (this.options.leading && this.canLeadingExecute) {
42
+ this.executeFunction(...args);
43
+ this.canLeadingExecute = false;
44
+ }
45
+ if (this.timeoutId) clearTimeout(this.timeoutId);
46
+ this.timeoutId = setTimeout(() => {
47
+ this.canLeadingExecute = true;
48
+ if (this.options.trailing) {
49
+ this.executeFunction(...args);
50
+ }
51
+ }, this.options.wait);
52
+ }
53
+ executeFunction(...args) {
54
+ if (!this.options.enabled) return;
55
+ this.executionCount++;
56
+ this.fn(...args);
57
+ }
58
+ /**
59
+ * Cancels any pending execution
60
+ */
61
+ cancel() {
62
+ if (this.timeoutId) {
63
+ clearTimeout(this.timeoutId);
64
+ this.canLeadingExecute = true;
65
+ }
66
+ }
67
+ }
68
+ function debounce(fn, initialOptions) {
69
+ const debouncer = new Debouncer(fn, initialOptions);
70
+ return debouncer.maybeExecute.bind(debouncer);
71
+ }
72
+ exports.Debouncer = Debouncer;
73
+ exports.debounce = debounce;
74
+ //# sourceMappingURL=debouncer.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debouncer.cjs","sources":["../../src/debouncer.ts"],"sourcesContent":["/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds before executing the function\n * Defaults to 0ms\n */\n wait: number\n}\n\nconst defaultOptions: Required<DebouncerOptions> = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a debounced function.\n *\n * Debouncing ensures that a function is only executed after a certain amount of time has passed\n * since its last invocation. This is useful for handling frequent events like window resizing,\n * scroll events, or input changes where you want to limit the rate of execution.\n *\n * The debounced function can be configured to execute either at the start of the delay period\n * (leading edge) or at the end (trailing edge, default). Each new call during the wait period\n * will reset the timer.\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer((value: string) => {\n * saveToDatabase(value);\n * }, { wait: 500 });\n *\n * // Will only save after 500ms of no new input\n * inputElement.addEventListener('input', () => {\n * debouncer.maybeExecute(inputElement.value);\n * });\n * ```\n */\nexport class Debouncer<\n TFn extends (...args: Array<any>) => any,\n TArgs extends Parameters<TFn>,\n> {\n private canLeadingExecute = true\n private executionCount = 0\n private options: Required<DebouncerOptions>\n private timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: DebouncerOptions,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<DebouncerOptions>,\n ): Required<DebouncerOptions> {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this.executionCount\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n maybeExecute(...args: TArgs): void {\n // Handle leading execution\n if (this.options.leading && this.canLeadingExecute) {\n this.executeFunction(...args)\n this.canLeadingExecute = false\n }\n\n // Clear any existing timeout\n if (this.timeoutId) clearTimeout(this.timeoutId)\n\n // Set new timeout that will reset canLeadingExecute\n this.timeoutId = setTimeout(() => {\n this.canLeadingExecute = true\n // Execute trailing only if enabled\n if (this.options.trailing) {\n this.executeFunction(...args)\n }\n }, this.options.wait)\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this.options.enabled) return\n this.executionCount++\n this.fn(...args)\n }\n\n /**\n * Cancels any pending execution\n */\n cancel(): void {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.canLeadingExecute = true\n }\n }\n}\n\n/**\n * Creates a debounced function that delays invoking the provided function until after a specified wait time.\n * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.\n *\n * This the the simple function wrapper implementation pulled from the Debouncer class. If you need\n * more control over the debouncing behavior, use the Debouncer class directly.\n *\n * If leading option is true, the function will execute immediately on the first call, then wait the delay\n * before allowing another execution.\n *\n * @example\n * ```ts\n * const debounced = debounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debounced);\n * ```\n */\nexport function debounce<TFn extends (...args: Array<any>) => any>(\n fn: TFn,\n initialOptions: Omit<DebouncerOptions, 'enabled'>,\n)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AAA,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;;;"}
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Options for configuring a debounced function
3
+ */
4
+ export interface DebouncerOptions {
5
+ /**
6
+ * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
7
+ * Defaults to true.
8
+ */
9
+ enabled?: boolean;
10
+ /**
11
+ * Whether to execute on the leading edge of the timeout.
12
+ * Defaults to false.
13
+ */
14
+ leading?: boolean;
15
+ /**
16
+ * Whether to execute on the trailing edge of the timeout.
17
+ * Defaults to true.
18
+ */
19
+ trailing?: boolean;
20
+ /**
21
+ * Delay in milliseconds before executing the function
22
+ * Defaults to 0ms
23
+ */
24
+ wait: number;
25
+ }
26
+ /**
27
+ * A class that creates a debounced function.
28
+ *
29
+ * Debouncing ensures that a function is only executed after a certain amount of time has passed
30
+ * since its last invocation. This is useful for handling frequent events like window resizing,
31
+ * scroll events, or input changes where you want to limit the rate of execution.
32
+ *
33
+ * The debounced function can be configured to execute either at the start of the delay period
34
+ * (leading edge) or at the end (trailing edge, default). Each new call during the wait period
35
+ * will reset the timer.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const debouncer = new Debouncer((value: string) => {
40
+ * saveToDatabase(value);
41
+ * }, { wait: 500 });
42
+ *
43
+ * // Will only save after 500ms of no new input
44
+ * inputElement.addEventListener('input', () => {
45
+ * debouncer.maybeExecute(inputElement.value);
46
+ * });
47
+ * ```
48
+ */
49
+ export declare class Debouncer<TFn extends (...args: Array<any>) => any, TArgs extends Parameters<TFn>> {
50
+ private fn;
51
+ private canLeadingExecute;
52
+ private executionCount;
53
+ private options;
54
+ private timeoutId;
55
+ constructor(fn: TFn, initialOptions: DebouncerOptions);
56
+ /**
57
+ * Updates the debouncer options
58
+ * Returns the new options state
59
+ */
60
+ setOptions(newOptions: Partial<DebouncerOptions>): Required<DebouncerOptions>;
61
+ /**
62
+ * Returns the number of times the function has been executed
63
+ */
64
+ getExecutionCount(): number;
65
+ /**
66
+ * Attempts to execute the debounced function
67
+ * If a call is already in progress, it will be queued
68
+ */
69
+ maybeExecute(...args: TArgs): void;
70
+ private executeFunction;
71
+ /**
72
+ * Cancels any pending execution
73
+ */
74
+ cancel(): void;
75
+ }
76
+ /**
77
+ * Creates a debounced function that delays invoking the provided function until after a specified wait time.
78
+ * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
79
+ *
80
+ * This the the simple function wrapper implementation pulled from the Debouncer class. If you need
81
+ * more control over the debouncing behavior, use the Debouncer class directly.
82
+ *
83
+ * If leading option is true, the function will execute immediately on the first call, then wait the delay
84
+ * before allowing another execution.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * const debounced = debounce(() => {
89
+ * saveChanges();
90
+ * }, { wait: 1000 });
91
+ *
92
+ * // Called repeatedly but executes at most once per second
93
+ * inputElement.addEventListener('input', debounced);
94
+ * ```
95
+ */
96
+ export declare function debounce<TFn extends (...args: Array<any>) => any>(fn: TFn, initialOptions: Omit<DebouncerOptions, 'enabled'>): (...args: Parameters<TFn>) => void;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const asyncDebouncer = require("./async-debouncer.cjs");
4
+ const asyncQueuer = require("./async-queuer.cjs");
5
+ const asyncRateLimiter = require("./async-rate-limiter.cjs");
6
+ const asyncThrottler = require("./async-throttler.cjs");
7
+ const compare = require("./compare.cjs");
8
+ const debouncer = require("./debouncer.cjs");
9
+ const queuer = require("./queuer.cjs");
10
+ const rateLimiter = require("./rate-limiter.cjs");
11
+ const throttler = require("./throttler.cjs");
12
+ exports.AsyncDebouncer = asyncDebouncer.AsyncDebouncer;
13
+ exports.asyncDebounce = asyncDebouncer.asyncDebounce;
14
+ exports.AsyncQueuer = asyncQueuer.AsyncQueuer;
15
+ exports.asyncQueue = asyncQueuer.asyncQueue;
16
+ exports.AsyncRateLimiter = asyncRateLimiter.AsyncRateLimiter;
17
+ exports.asyncRateLimit = asyncRateLimiter.asyncRateLimit;
18
+ exports.AsyncThrottler = asyncThrottler.AsyncThrottler;
19
+ exports.asyncThrottle = asyncThrottler.asyncThrottle;
20
+ exports.isPlainArray = compare.isPlainArray;
21
+ exports.isPlainObject = compare.isPlainObject;
22
+ exports.replaceEqualDeep = compare.replaceEqualDeep;
23
+ exports.shallowEqualObjects = compare.shallowEqualObjects;
24
+ exports.Debouncer = debouncer.Debouncer;
25
+ exports.debounce = debouncer.debounce;
26
+ exports.Queuer = queuer.Queuer;
27
+ exports.queue = queuer.queue;
28
+ exports.RateLimiter = rateLimiter.RateLimiter;
29
+ exports.rateLimit = rateLimiter.rateLimit;
30
+ exports.Throttler = throttler.Throttler;
31
+ exports.throttle = throttler.throttle;
32
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,9 @@
1
+ export * from './async-debouncer.cjs';
2
+ export * from './async-queuer.cjs';
3
+ export * from './async-rate-limiter.cjs';
4
+ export * from './async-throttler.cjs';
5
+ export * from './compare.cjs';
6
+ export * from './debouncer.cjs';
7
+ export * from './queuer.cjs';
8
+ export * from './rate-limiter.cjs';
9
+ export * from './throttler.cjs';
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const defaultOptions = {
4
+ addItemsTo: "back",
5
+ getItemsFrom: "front",
6
+ getPriority: () => 0,
7
+ initialItems: [],
8
+ maxSize: Infinity,
9
+ onGetNextItem: () => {
10
+ },
11
+ onUpdate: () => {
12
+ },
13
+ started: false,
14
+ wait: 0
15
+ };
16
+ class Queuer {
17
+ constructor(initialOptions = defaultOptions) {
18
+ this.items = [];
19
+ this.executionCount = 0;
20
+ this.onUpdates = [];
21
+ this.pendingTick = false;
22
+ this.options = { ...defaultOptions, ...initialOptions };
23
+ this.running = this.options.started;
24
+ for (let i = 0; i < this.options.initialItems.length; i++) {
25
+ const item = this.options.initialItems[i];
26
+ const isLast = i === this.options.initialItems.length - 1;
27
+ this.addItem(item, this.options.addItemsTo, isLast);
28
+ }
29
+ }
30
+ /**
31
+ * Processes items in the queuer
32
+ */
33
+ tick() {
34
+ if (!this.running) {
35
+ this.pendingTick = false;
36
+ return;
37
+ }
38
+ while (!this.isEmpty()) {
39
+ const nextItem = this.getNextItem(this.options.getItemsFrom);
40
+ if (nextItem === void 0) {
41
+ break;
42
+ }
43
+ this.onUpdates.forEach((cb) => cb(nextItem));
44
+ if (this.options.wait > 0) {
45
+ setTimeout(() => this.tick(), this.options.wait);
46
+ return;
47
+ }
48
+ this.tick();
49
+ }
50
+ this.pendingTick = false;
51
+ }
52
+ /**
53
+ * Updates the queuer options
54
+ * Returns the new options state
55
+ */
56
+ setOptions(newOptions) {
57
+ this.options = { ...this.options, ...newOptions };
58
+ return this.options;
59
+ }
60
+ /**
61
+ * Adds an item to the queuer and starts processing if not already running
62
+ * @returns true if item was added, false if queuer is full
63
+ */
64
+ addItem(item, position = this.options.addItemsTo, runOnUpdate = true) {
65
+ if (this.isFull()) {
66
+ return false;
67
+ }
68
+ if (this.options.getPriority !== defaultOptions.getPriority) {
69
+ const priority = this.options.getPriority(item);
70
+ const insertIndex = this.items.findIndex(
71
+ (existing) => this.options.getPriority(existing) > priority
72
+ );
73
+ if (insertIndex === -1) {
74
+ this.items.push(item);
75
+ } else {
76
+ this.items.splice(insertIndex, 0, item);
77
+ }
78
+ } else {
79
+ if (position === "front") {
80
+ this.items.unshift(item);
81
+ } else {
82
+ this.items.push(item);
83
+ }
84
+ }
85
+ if (this.running && !this.pendingTick) {
86
+ this.pendingTick = true;
87
+ this.tick();
88
+ }
89
+ if (runOnUpdate) {
90
+ this.options.onUpdate(this);
91
+ }
92
+ return true;
93
+ }
94
+ /**
95
+ * Removes and returns an item from the queuer using shift (default) or pop
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * // Standard FIFO queuer
100
+ * queuer.getNextItem()
101
+ * // Stack-like behavior (LIFO)
102
+ * queuer.getNextItem('back')
103
+ * ```
104
+ */
105
+ getNextItem(position = this.options.getItemsFrom) {
106
+ let item;
107
+ if (position === "front") {
108
+ item = this.items.shift();
109
+ } else {
110
+ item = this.items.pop();
111
+ }
112
+ if (item !== void 0) {
113
+ this.executionCount++;
114
+ this.options.onUpdate(this);
115
+ this.options.onGetNextItem(item, this);
116
+ }
117
+ return item;
118
+ }
119
+ /**
120
+ * Returns an item without removing it
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * // Look at next item to getNextItem
125
+ * queuer.peek()
126
+ * // Look at last item (like stack top)
127
+ * queuer.peek('back')
128
+ * ```
129
+ */
130
+ peek(position = this.options.getItemsFrom) {
131
+ if (position === "front") {
132
+ return this.items[0];
133
+ }
134
+ return this.items[this.items.length - 1];
135
+ }
136
+ /**
137
+ * Returns true if the queuer is empty
138
+ */
139
+ isEmpty() {
140
+ return this.items.length === 0;
141
+ }
142
+ /**
143
+ * Returns true if the queuer is full
144
+ */
145
+ isFull() {
146
+ return this.items.length >= this.options.maxSize;
147
+ }
148
+ /**
149
+ * Returns the current size of the queuer
150
+ */
151
+ size() {
152
+ return this.items.length;
153
+ }
154
+ /**
155
+ * Removes all items from the queuer
156
+ */
157
+ clear() {
158
+ this.items = [];
159
+ this.options.onUpdate(this);
160
+ }
161
+ /**
162
+ * Resets the queuer to its initial state
163
+ */
164
+ reset(withInitialItems) {
165
+ this.clear();
166
+ this.executionCount = 0;
167
+ if (withInitialItems) {
168
+ this.items = [...this.options.initialItems];
169
+ }
170
+ this.running = this.options.started;
171
+ }
172
+ /**
173
+ * Returns a copy of all items in the queuer
174
+ */
175
+ getAllItems() {
176
+ return [...this.items];
177
+ }
178
+ /**
179
+ * Returns the number of items that have been removed from the queuer
180
+ */
181
+ getExecutionCount() {
182
+ return this.executionCount;
183
+ }
184
+ /**
185
+ * Adds a callback to be called when an item is processed
186
+ */
187
+ onUpdate(cb) {
188
+ this.onUpdates.push(cb);
189
+ return () => {
190
+ this.onUpdates = this.onUpdates.filter((d) => d !== cb);
191
+ };
192
+ }
193
+ /**
194
+ * Stops the queuer from processing items
195
+ */
196
+ stop() {
197
+ this.running = false;
198
+ this.pendingTick = false;
199
+ this.options.onUpdate(this);
200
+ }
201
+ /**
202
+ * Starts the queuer and processes items
203
+ */
204
+ start() {
205
+ this.running = true;
206
+ if (!this.pendingTick && !this.isEmpty()) {
207
+ this.pendingTick = true;
208
+ this.tick();
209
+ }
210
+ this.options.onUpdate(this);
211
+ }
212
+ /**
213
+ * Returns true if the queuer is running
214
+ */
215
+ isRunning() {
216
+ return this.running;
217
+ }
218
+ /**
219
+ * Returns true if the queuer is running but has no items to process
220
+ */
221
+ isIdle() {
222
+ return this.running && this.isEmpty();
223
+ }
224
+ }
225
+ function queue(options = {}) {
226
+ const queuer = new Queuer({ ...options, started: true });
227
+ return queuer.addItem.bind(queuer);
228
+ }
229
+ exports.Queuer = Queuer;
230
+ exports.queue = queue;
231
+ //# sourceMappingURL=queuer.cjs.map