@tanstack/pacer 0.8.0 → 0.9.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.
- package/dist/cjs/async-batcher.cjs +163 -0
- package/dist/cjs/async-batcher.cjs.map +1 -0
- package/dist/cjs/async-batcher.d.cts +273 -0
- package/dist/cjs/async-debouncer.cjs +149 -162
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +76 -57
- package/dist/cjs/async-queuer.cjs +282 -343
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +121 -100
- package/dist/cjs/async-rate-limiter.cjs +128 -185
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +72 -61
- package/dist/cjs/async-throttler.cjs +168 -178
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +97 -69
- package/dist/cjs/batcher.cjs +110 -119
- package/dist/cjs/batcher.cjs.map +1 -1
- package/dist/cjs/batcher.d.cts +76 -51
- package/dist/cjs/debouncer.cjs +97 -85
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +54 -26
- package/dist/cjs/index.cjs +3 -6
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +1 -1
- package/dist/cjs/queuer.cjs +246 -294
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +102 -81
- package/dist/cjs/rate-limiter.cjs +97 -130
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +50 -37
- package/dist/cjs/throttler.cjs +107 -123
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +59 -35
- package/dist/cjs/utils.cjs +0 -13
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +0 -1
- package/dist/esm/async-batcher.d.ts +273 -0
- package/dist/esm/async-batcher.js +163 -0
- package/dist/esm/async-batcher.js.map +1 -0
- package/dist/esm/async-debouncer.d.ts +76 -57
- package/dist/esm/async-debouncer.js +149 -162
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +121 -100
- package/dist/esm/async-queuer.js +282 -343
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +72 -61
- package/dist/esm/async-rate-limiter.js +128 -185
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +97 -69
- package/dist/esm/async-throttler.js +168 -178
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/batcher.d.ts +76 -51
- package/dist/esm/batcher.js +110 -119
- package/dist/esm/batcher.js.map +1 -1
- package/dist/esm/debouncer.d.ts +54 -26
- package/dist/esm/debouncer.js +97 -85
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +4 -7
- package/dist/esm/queuer.d.ts +102 -81
- package/dist/esm/queuer.js +246 -294
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +50 -37
- package/dist/esm/rate-limiter.js +97 -130
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +59 -35
- package/dist/esm/throttler.js +107 -123
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/utils.d.ts +0 -1
- package/dist/esm/utils.js +0 -13
- package/dist/esm/utils.js.map +1 -1
- package/package.json +14 -11
- package/src/async-batcher.ts +475 -0
- package/src/async-debouncer.ts +201 -121
- package/src/async-queuer.ts +337 -216
- package/src/async-rate-limiter.ts +176 -136
- package/src/async-throttler.ts +233 -139
- package/src/batcher.ts +158 -92
- package/src/debouncer.ts +135 -52
- package/src/index.ts +1 -1
- package/src/queuer.ts +348 -226
- package/src/rate-limiter.ts +125 -80
- package/src/throttler.ts +152 -78
- package/src/utils.ts +0 -15
- package/dist/cjs/compare.cjs +0 -72
- package/dist/cjs/compare.cjs.map +0 -1
- package/dist/cjs/compare.d.cts +0 -12
- package/dist/esm/compare.d.ts +0 -12
- package/dist/esm/compare.js +0 -72
- package/dist/esm/compare.js.map +0 -1
- package/src/compare.ts +0 -105
package/dist/esm/batcher.js
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
+
import { Store } from "@tanstack/store";
|
|
2
|
+
import { parseFunctionOrValue } from "./utils.js";
|
|
3
|
+
function getDefaultBatcherState() {
|
|
4
|
+
return {
|
|
5
|
+
executionCount: 0,
|
|
6
|
+
isEmpty: true,
|
|
7
|
+
isPending: false,
|
|
8
|
+
isRunning: true,
|
|
9
|
+
totalItemsProcessed: 0,
|
|
10
|
+
items: [],
|
|
11
|
+
size: 0,
|
|
12
|
+
status: "idle"
|
|
13
|
+
};
|
|
14
|
+
}
|
|
1
15
|
const defaultOptions = {
|
|
2
16
|
getShouldExecute: () => false,
|
|
3
17
|
maxSize: Infinity,
|
|
@@ -7,129 +21,106 @@ const defaultOptions = {
|
|
|
7
21
|
class Batcher {
|
|
8
22
|
constructor(fn, initialOptions) {
|
|
9
23
|
this.fn = fn;
|
|
10
|
-
this.
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
this
|
|
14
|
-
this.
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
this.
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
this.
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
* Returns true if the batcher is empty
|
|
101
|
-
*/
|
|
102
|
-
getIsEmpty() {
|
|
103
|
-
return this._items.length === 0;
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* Returns true if the batcher is running
|
|
107
|
-
*/
|
|
108
|
-
getIsRunning() {
|
|
109
|
-
return this._running;
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Returns a copy of all items currently in the batcher
|
|
113
|
-
*/
|
|
114
|
-
peekAllItems() {
|
|
115
|
-
return [...this._items];
|
|
116
|
-
}
|
|
117
|
-
/**
|
|
118
|
-
* Returns the number of times batches have been processed
|
|
119
|
-
*/
|
|
120
|
-
getBatchExecutionCount() {
|
|
121
|
-
return this._batchExecutionCount;
|
|
122
|
-
}
|
|
123
|
-
/**
|
|
124
|
-
* Returns the total number of individual items that have been processed
|
|
125
|
-
*/
|
|
126
|
-
getItemExecutionCount() {
|
|
127
|
-
return this._itemExecutionCount;
|
|
24
|
+
this.store = new Store(
|
|
25
|
+
getDefaultBatcherState()
|
|
26
|
+
);
|
|
27
|
+
this.#timeoutId = null;
|
|
28
|
+
this.setOptions = (newOptions) => {
|
|
29
|
+
this.options = { ...this.options, ...newOptions };
|
|
30
|
+
};
|
|
31
|
+
this.#setState = (newState) => {
|
|
32
|
+
this.store.setState((state) => {
|
|
33
|
+
const combinedState = {
|
|
34
|
+
...state,
|
|
35
|
+
...newState
|
|
36
|
+
};
|
|
37
|
+
const { isPending, items } = combinedState;
|
|
38
|
+
const size = items.length;
|
|
39
|
+
const isEmpty = size === 0;
|
|
40
|
+
return {
|
|
41
|
+
...combinedState,
|
|
42
|
+
isEmpty,
|
|
43
|
+
size,
|
|
44
|
+
status: isPending ? "pending" : "idle"
|
|
45
|
+
};
|
|
46
|
+
});
|
|
47
|
+
};
|
|
48
|
+
this.#getWait = () => {
|
|
49
|
+
return parseFunctionOrValue(this.options.wait, this);
|
|
50
|
+
};
|
|
51
|
+
this.addItem = (item) => {
|
|
52
|
+
this.#setState({
|
|
53
|
+
items: [...this.store.state.items, item],
|
|
54
|
+
isPending: this.options.wait !== Infinity
|
|
55
|
+
});
|
|
56
|
+
this.options.onItemsChange?.(this);
|
|
57
|
+
const shouldProcess = this.store.state.items.length >= this.options.maxSize || this.options.getShouldExecute(this.store.state.items, this);
|
|
58
|
+
if (shouldProcess) {
|
|
59
|
+
this.#execute();
|
|
60
|
+
} else if (this.store.state.isRunning && this.options.wait !== Infinity) {
|
|
61
|
+
this.#clearTimeout();
|
|
62
|
+
this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait());
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
this.#execute = () => {
|
|
66
|
+
if (this.store.state.items.length === 0) {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const batch2 = this.peekAllItems();
|
|
70
|
+
this.clear();
|
|
71
|
+
this.options.onItemsChange?.(this);
|
|
72
|
+
this.fn(batch2);
|
|
73
|
+
this.#setState({
|
|
74
|
+
executionCount: this.store.state.executionCount + 1,
|
|
75
|
+
totalItemsProcessed: this.store.state.totalItemsProcessed + batch2.length
|
|
76
|
+
});
|
|
77
|
+
this.options.onExecute?.(this);
|
|
78
|
+
};
|
|
79
|
+
this.flush = () => {
|
|
80
|
+
this.#clearTimeout();
|
|
81
|
+
this.#execute();
|
|
82
|
+
};
|
|
83
|
+
this.stop = () => {
|
|
84
|
+
this.#setState({ isRunning: false });
|
|
85
|
+
this.#clearTimeout();
|
|
86
|
+
};
|
|
87
|
+
this.start = () => {
|
|
88
|
+
this.#setState({ isRunning: true });
|
|
89
|
+
if (this.store.state.items.length > 0) {
|
|
90
|
+
this.#execute();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
this.peekAllItems = () => {
|
|
94
|
+
return [...this.store.state.items];
|
|
95
|
+
};
|
|
96
|
+
this.#clearTimeout = () => {
|
|
97
|
+
if (this.#timeoutId) {
|
|
98
|
+
clearTimeout(this.#timeoutId);
|
|
99
|
+
this.#timeoutId = null;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
this.clear = () => {
|
|
103
|
+
this.#setState({ items: [], isPending: false });
|
|
104
|
+
};
|
|
105
|
+
this.reset = () => {
|
|
106
|
+
this.#setState(getDefaultBatcherState());
|
|
107
|
+
this.options.onItemsChange?.(this);
|
|
108
|
+
};
|
|
109
|
+
this.options = {
|
|
110
|
+
...defaultOptions,
|
|
111
|
+
...initialOptions
|
|
112
|
+
};
|
|
113
|
+
this.#setState(this.options.initialState ?? {});
|
|
128
114
|
}
|
|
115
|
+
#timeoutId;
|
|
116
|
+
#setState;
|
|
117
|
+
#getWait;
|
|
118
|
+
#execute;
|
|
119
|
+
#clearTimeout;
|
|
129
120
|
}
|
|
130
121
|
function batch(fn, options) {
|
|
131
122
|
const batcher = new Batcher(fn, options);
|
|
132
|
-
return batcher.addItem
|
|
123
|
+
return batcher.addItem;
|
|
133
124
|
}
|
|
134
125
|
export {
|
|
135
126
|
Batcher,
|
package/dist/esm/batcher.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"batcher.js","sources":["../../src/batcher.ts"],"sourcesContent":["import type { OptionalKeys } from './types'\n\n/**\n * Options for configuring a Batcher instance\n */\nexport interface BatcherOptions<TValue> {\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Callback fired after a batch is processed\n */\n onExecute?: (batcher: Batcher<TValue>) => void\n /**\n * Callback fired when the batcher's running state changes\n */\n onIsRunningChange?: (batcher: Batcher<TValue>) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: Batcher<TValue>) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\n */\n started?: boolean\n /**\n * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number\n}\n\ntype BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<BatcherOptions<TValue>>,\n 'onExecute' | 'onItemsChange' | 'onIsRunningChange'\n>\n\nconst defaultOptions: BatcherOptionsWithOptionalCallbacks<any> = {\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches.\n *\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n *\n * The Batcher provides a flexible way to implement batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n *\n * @example\n * ```ts\n * const batcher = new Batcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecuteBatch: (items) => console.log('Batch executed:', items)\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed\n * // batcher.execute() // manually trigger a batch\n * ```\n */\nexport class Batcher<TValue> {\n private _options: BatcherOptionsWithOptionalCallbacks<TValue>\n private _batchExecutionCount = 0\n private _itemExecutionCount = 0\n private _items: Array<TValue> = []\n private _running: boolean\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue>,\n ) {\n this._options = { ...defaultOptions, ...initialOptions }\n this._running = this._options.started\n }\n\n /**\n * Updates the batcher options\n */\n setOptions(newOptions: Partial<BatcherOptions<TValue>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current batcher options\n */\n getOptions(): BatcherOptions<TValue> {\n return this._options\n }\n\n /**\n * Adds an item to the batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n */\n addItem(item: TValue): void {\n this._items.push(item)\n this._options.onItemsChange?.(this)\n\n const shouldProcess =\n this._items.length >= this._options.maxSize ||\n this._options.getShouldExecute(this._items, this)\n\n if (shouldProcess) {\n this.execute()\n } else if (\n this._running &&\n !this._timeoutId &&\n this._options.wait !== Infinity\n ) {\n this._timeoutId = setTimeout(() => this.execute(), this._options.wait)\n }\n }\n\n /**\n * Processes the current batch of items.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches batchSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n */\n execute(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n\n if (this._items.length === 0) {\n return\n }\n\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this._items = [] // Clear items before processing to prevent race conditions\n this._options.onItemsChange?.(this) // Call onItemsChange to notify listeners that the items have changed\n\n this.fn(batch)\n this._batchExecutionCount++\n this._itemExecutionCount += batch.length\n this._options.onExecute?.(this)\n }\n\n /**\n * Stops the batcher from processing batches\n */\n stop(): void {\n this._running = false\n this._options.onIsRunningChange?.(this)\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n }\n\n /**\n * Starts the batcher and processes any pending items\n */\n start(): void {\n this._running = true\n this._options.onIsRunningChange?.(this)\n if (this._items.length > 0 && !this._timeoutId) {\n this._timeoutId = setTimeout(() => this.execute(), this._options.wait)\n }\n }\n\n /**\n * Returns the current number of items in the batcher\n */\n getSize(): number {\n return this._items.length\n }\n\n /**\n * Returns true if the batcher is empty\n */\n getIsEmpty(): boolean {\n return this._items.length === 0\n }\n\n /**\n * Returns true if the batcher is running\n */\n getIsRunning(): boolean {\n return this._running\n }\n\n /**\n * Returns a copy of all items currently in the batcher\n */\n peekAllItems(): Array<TValue> {\n return [...this._items]\n }\n\n /**\n * Returns the number of times batches have been processed\n */\n getBatchExecutionCount(): number {\n return this._batchExecutionCount\n }\n\n /**\n * Returns the total number of individual items that have been processed\n */\n getItemExecutionCount(): number {\n return this._itemExecutionCount\n }\n}\n\n/**\n * Creates a batcher that processes items in batches\n *\n * @example\n * ```ts\n * const batchItems = batch<number>({\n * batchSize: 3,\n * processBatch: (items) => console.log('Processing:', items)\n * });\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function batch<TValue>(\n fn: (items: Array<TValue>) => void,\n options: BatcherOptions<TValue>,\n) {\n const batcher = new Batcher<TValue>(fn, options)\n return batcher.addItem.bind(batcher)\n}\n"],"names":["batch"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"batcher.js","sources":["../../src/batcher.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport type { OptionalKeys } from './types'\n\nexport interface BatcherState<TValue> {\n /**\n * Number of batch executions that have been completed\n */\n executionCount: number\n /**\n * Whether the batcher has no items to process (items array is empty)\n */\n isEmpty: boolean\n /**\n * Whether the batcher is waiting for the timeout to trigger batch processing\n */\n isPending: boolean\n /**\n * Whether the batcher is active and will process items automatically\n */\n isRunning: boolean\n /**\n * Total number of items that have been processed across all batches\n */\n totalItemsProcessed: number\n /**\n * Array of items currently queued for batch processing\n */\n items: Array<TValue>\n /**\n * Number of items currently in the batch queue\n */\n size: number\n /**\n * Current processing status - 'idle' when not processing, 'pending' when waiting for timeout\n */\n status: 'idle' | 'pending'\n}\n\nfunction getDefaultBatcherState<TValue>(): BatcherState<TValue> {\n return {\n executionCount: 0,\n isEmpty: true,\n isPending: false,\n isRunning: true,\n totalItemsProcessed: 0,\n items: [],\n size: 0,\n status: 'idle',\n }\n}\n\n/**\n * Options for configuring a Batcher instance\n */\nexport interface BatcherOptions<TValue> {\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean\n /**\n * Initial state for the batcher\n */\n initialState?: Partial<BatcherState<TValue>>\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Callback fired after a batch is processed\n */\n onExecute?: (batcher: Batcher<TValue>) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: Batcher<TValue>) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\n */\n started?: boolean\n /**\n * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number | ((batcher: Batcher<TValue>) => number)\n}\n\ntype BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<\n Required<BatcherOptions<TValue>>,\n 'initialState' | 'onExecute' | 'onItemsChange'\n>\n\nconst defaultOptions: BatcherOptionsWithOptionalCallbacks<any> = {\n getShouldExecute: () => false,\n maxSize: Infinity,\n started: true,\n wait: Infinity,\n}\n\n/**\n * A class that collects items and processes them in batches.\n *\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n *\n * The Batcher provides a flexible way to implement batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n *\n * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the batcher\n * - Use `onExecute` callback to react to batch execution and implement custom logic\n * - Use `onItemsChange` callback to react to items being added or removed from the batcher\n * - The state includes batch execution count, total items processed, items, and running status\n * - State can be accessed via `batcher.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `batcher.state`\n *\n * @example\n * ```ts\n * const batcher = new Batcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batcher) => console.log('Batch executed:', batcher.peekAllItems())\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed\n * // batcher.flush() // manually trigger a batch\n * ```\n */\nexport class Batcher<TValue> {\n readonly store: Store<Readonly<BatcherState<TValue>>> = new Store(\n getDefaultBatcherState<TValue>(),\n )\n options: BatcherOptionsWithOptionalCallbacks<TValue>\n #timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: (items: Array<TValue>) => void,\n initialOptions: BatcherOptions<TValue>,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n this.#setState(this.options.initialState ?? {})\n }\n\n /**\n * Updates the batcher options\n */\n setOptions = (newOptions: Partial<BatcherOptions<TValue>>): void => {\n this.options = { ...this.options, ...newOptions }\n }\n\n #setState = (newState: Partial<BatcherState<TValue>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending, items } = combinedState\n const size = items.length\n const isEmpty = size === 0\n return {\n ...combinedState,\n isEmpty,\n size,\n status: isPending ? 'pending' : 'idle',\n }\n })\n }\n\n #getWait = (): number => {\n return parseFunctionOrValue(this.options.wait, this)\n }\n\n /**\n * Adds an item to the batcher\n * If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed\n */\n addItem = (item: TValue): void => {\n this.#setState({\n items: [...this.store.state.items, item],\n isPending: this.options.wait !== Infinity,\n })\n this.options.onItemsChange?.(this)\n\n const shouldProcess =\n this.store.state.items.length >= this.options.maxSize ||\n this.options.getShouldExecute(this.store.state.items, this)\n\n if (shouldProcess) {\n this.#execute()\n } else if (this.store.state.isRunning && this.options.wait !== Infinity) {\n this.#clearTimeout() // clear any pending timeout to replace it with a new one\n this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait())\n }\n }\n\n /**\n * Processes the current batch of items.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches batchSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n */\n #execute = (): void => {\n if (this.store.state.items.length === 0) {\n return\n }\n\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this.clear() // Clear items before processing to prevent race conditions\n this.options.onItemsChange?.(this) // Call onItemsChange to notify listeners that the items have changed\n\n this.fn(batch) // EXECUTE\n this.#setState({\n executionCount: this.store.state.executionCount + 1,\n totalItemsProcessed: this.store.state.totalItemsProcessed + batch.length,\n })\n this.options.onExecute?.(this)\n }\n\n /**\n * Processes the current batch of items immediately\n */\n flush = (): void => {\n this.#clearTimeout() // clear any pending timeout\n this.#execute() // execute immediately\n }\n\n /**\n * Stops the batcher from processing batches\n */\n stop = (): void => {\n this.#setState({ isRunning: false })\n this.#clearTimeout()\n }\n\n /**\n * Starts the batcher and processes any pending items\n */\n start = (): void => {\n this.#setState({ isRunning: true })\n if (this.store.state.items.length > 0) {\n this.#execute()\n }\n }\n\n /**\n * Returns a copy of all items in the batcher\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.store.state.items]\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = null\n }\n }\n\n /**\n * Removes all items from the batcher\n */\n clear = (): void => {\n this.#setState({ items: [], isPending: false })\n }\n\n /**\n * Resets the batcher state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultBatcherState<TValue>())\n this.options.onItemsChange?.(this)\n }\n}\n\n/**\n * Creates a batcher that processes items in batches\n *\n * @example\n * ```ts\n * const batchItems = batch<number>(\n * (items) => console.log('Processing:', items),\n * {\n * maxSize: 3,\n * onExecute: (batcher) => console.log('Batch executed')\n * }\n * );\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function batch<TValue>(\n fn: (items: Array<TValue>) => void,\n options: BatcherOptions<TValue>,\n) {\n const batcher = new Batcher<TValue>(fn, options)\n return batcher.addItem\n}\n"],"names":["batch"],"mappings":"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"}
|
package/dist/esm/debouncer.d.ts
CHANGED
|
@@ -1,4 +1,27 @@
|
|
|
1
|
+
import { Store } from '@tanstack/store';
|
|
1
2
|
import { AnyFunction } from './types.js';
|
|
3
|
+
export interface DebouncerState<TFn extends AnyFunction> {
|
|
4
|
+
/**
|
|
5
|
+
* Whether the debouncer can execute on the leading edge of the timeout
|
|
6
|
+
*/
|
|
7
|
+
canLeadingExecute: boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Number of function executions that have been completed
|
|
10
|
+
*/
|
|
11
|
+
executionCount: number;
|
|
12
|
+
/**
|
|
13
|
+
* Whether the debouncer is waiting for the timeout to trigger execution
|
|
14
|
+
*/
|
|
15
|
+
isPending: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* The arguments from the most recent call to maybeExecute
|
|
18
|
+
*/
|
|
19
|
+
lastArgs: Parameters<TFn> | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* Current execution status - 'idle' when not active, 'pending' when waiting for timeout
|
|
22
|
+
*/
|
|
23
|
+
status: 'disabled' | 'idle' | 'pending';
|
|
24
|
+
}
|
|
2
25
|
/**
|
|
3
26
|
* Options for configuring a debounced function
|
|
4
27
|
*/
|
|
@@ -9,6 +32,10 @@ export interface DebouncerOptions<TFn extends AnyFunction> {
|
|
|
9
32
|
* Defaults to true.
|
|
10
33
|
*/
|
|
11
34
|
enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean);
|
|
35
|
+
/**
|
|
36
|
+
* Initial state for the debouncer
|
|
37
|
+
*/
|
|
38
|
+
initialState?: Partial<DebouncerState<TFn>>;
|
|
12
39
|
/**
|
|
13
40
|
* Whether to execute on the leading edge of the timeout.
|
|
14
41
|
* The first call will execute immediately and the rest will wait the delay.
|
|
@@ -42,6 +69,14 @@ export interface DebouncerOptions<TFn extends AnyFunction> {
|
|
|
42
69
|
* (leading edge) or at the end (trailing edge, default). Each new call during the wait period
|
|
43
70
|
* will reset the timer.
|
|
44
71
|
*
|
|
72
|
+
* State Management:
|
|
73
|
+
* - Uses TanStack Store for reactive state management
|
|
74
|
+
* - Use `initialState` to provide initial state values when creating the debouncer
|
|
75
|
+
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
76
|
+
* - The state includes canLeadingExecute, execution count, and isPending status
|
|
77
|
+
* - State can be accessed via `debouncer.store.state` when using the class directly
|
|
78
|
+
* - When using framework adapters (React/Solid), state is accessed from `debouncer.state`
|
|
79
|
+
*
|
|
45
80
|
* @example
|
|
46
81
|
* ```ts
|
|
47
82
|
* const debouncer = new Debouncer((value: string) => {
|
|
@@ -55,47 +90,32 @@ export interface DebouncerOptions<TFn extends AnyFunction> {
|
|
|
55
90
|
* ```
|
|
56
91
|
*/
|
|
57
92
|
export declare class Debouncer<TFn extends AnyFunction> {
|
|
93
|
+
#private;
|
|
58
94
|
private fn;
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
private _isPending;
|
|
62
|
-
private _options;
|
|
63
|
-
private _timeoutId;
|
|
95
|
+
readonly store: Store<Readonly<DebouncerState<TFn>>>;
|
|
96
|
+
options: DebouncerOptions<TFn>;
|
|
64
97
|
constructor(fn: TFn, initialOptions: DebouncerOptions<TFn>);
|
|
65
98
|
/**
|
|
66
99
|
* Updates the debouncer options
|
|
67
100
|
*/
|
|
68
|
-
setOptions(newOptions: Partial<DebouncerOptions<TFn>>)
|
|
69
|
-
/**
|
|
70
|
-
* Returns the current debouncer options
|
|
71
|
-
*/
|
|
72
|
-
getOptions(): Required<DebouncerOptions<TFn>>;
|
|
73
|
-
/**
|
|
74
|
-
* Returns the current enabled state of the debouncer
|
|
75
|
-
*/
|
|
76
|
-
getEnabled(): boolean;
|
|
77
|
-
/**
|
|
78
|
-
* Returns the current wait time in milliseconds
|
|
79
|
-
*/
|
|
80
|
-
getWait(): number;
|
|
101
|
+
setOptions: (newOptions: Partial<DebouncerOptions<TFn>>) => void;
|
|
81
102
|
/**
|
|
82
103
|
* Attempts to execute the debounced function
|
|
83
104
|
* If a call is already in progress, it will be queued
|
|
84
105
|
*/
|
|
85
|
-
maybeExecute(...args: Parameters<TFn>)
|
|
86
|
-
private execute;
|
|
106
|
+
maybeExecute: (...args: Parameters<TFn>) => void;
|
|
87
107
|
/**
|
|
88
|
-
*
|
|
108
|
+
* Processes the current pending execution immediately
|
|
89
109
|
*/
|
|
90
|
-
|
|
110
|
+
flush: () => void;
|
|
91
111
|
/**
|
|
92
|
-
*
|
|
112
|
+
* Cancels any pending execution
|
|
93
113
|
*/
|
|
94
|
-
|
|
114
|
+
cancel: () => void;
|
|
95
115
|
/**
|
|
96
|
-
*
|
|
116
|
+
* Resets the debouncer state to its default values
|
|
97
117
|
*/
|
|
98
|
-
|
|
118
|
+
reset: () => void;
|
|
99
119
|
}
|
|
100
120
|
/**
|
|
101
121
|
* Creates a debounced function that delays invoking the provided function until after a specified wait time.
|
|
@@ -107,6 +127,14 @@ export declare class Debouncer<TFn extends AnyFunction> {
|
|
|
107
127
|
* If leading option is true, the function will execute immediately on the first call, then wait the delay
|
|
108
128
|
* before allowing another execution.
|
|
109
129
|
*
|
|
130
|
+
* State Management:
|
|
131
|
+
* - Uses TanStack Store for reactive state management
|
|
132
|
+
* - Use `initialState` to provide initial state values when creating the debouncer
|
|
133
|
+
* - Use `onExecute` callback to react to function execution and implement custom logic
|
|
134
|
+
* - The state includes canLeadingExecute, execution count, and isPending status
|
|
135
|
+
* - State can be accessed via the underlying Debouncer instance's `store.state` property
|
|
136
|
+
* - When using framework adapters (React/Solid), state is accessed from the hook's state property
|
|
137
|
+
*
|
|
110
138
|
* @example
|
|
111
139
|
* ```ts
|
|
112
140
|
* const debounced = debounce(() => {
|
package/dist/esm/debouncer.js
CHANGED
|
@@ -1,105 +1,117 @@
|
|
|
1
|
+
import { Store } from "@tanstack/store";
|
|
1
2
|
import { parseFunctionOrValue } from "./utils.js";
|
|
3
|
+
function getDefaultDebouncerState() {
|
|
4
|
+
return structuredClone({
|
|
5
|
+
canLeadingExecute: true,
|
|
6
|
+
executionCount: 0,
|
|
7
|
+
isPending: false,
|
|
8
|
+
lastArgs: void 0,
|
|
9
|
+
status: "idle"
|
|
10
|
+
});
|
|
11
|
+
}
|
|
2
12
|
const defaultOptions = {
|
|
3
13
|
enabled: true,
|
|
4
14
|
leading: false,
|
|
5
|
-
onExecute: () => {
|
|
6
|
-
},
|
|
7
15
|
trailing: true,
|
|
8
16
|
wait: 0
|
|
9
17
|
};
|
|
10
18
|
class Debouncer {
|
|
11
19
|
constructor(fn, initialOptions) {
|
|
12
20
|
this.fn = fn;
|
|
13
|
-
this.
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
this.
|
|
21
|
+
this.store = new Store(
|
|
22
|
+
getDefaultDebouncerState()
|
|
23
|
+
);
|
|
24
|
+
this.setOptions = (newOptions) => {
|
|
25
|
+
this.options = { ...this.options, ...newOptions };
|
|
26
|
+
if (!this.#getEnabled()) {
|
|
27
|
+
this.cancel();
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
this.#setState = (newState) => {
|
|
31
|
+
this.store.setState((state) => {
|
|
32
|
+
const combinedState = {
|
|
33
|
+
...state,
|
|
34
|
+
...newState
|
|
35
|
+
};
|
|
36
|
+
const { isPending } = combinedState;
|
|
37
|
+
return {
|
|
38
|
+
...combinedState,
|
|
39
|
+
status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
|
|
40
|
+
};
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
this.#getEnabled = () => {
|
|
44
|
+
return !!parseFunctionOrValue(this.options.enabled, this);
|
|
45
|
+
};
|
|
46
|
+
this.#getWait = () => {
|
|
47
|
+
return parseFunctionOrValue(this.options.wait, this);
|
|
48
|
+
};
|
|
49
|
+
this.maybeExecute = (...args) => {
|
|
50
|
+
if (!this.#getEnabled()) return void 0;
|
|
51
|
+
let _didLeadingExecute = false;
|
|
52
|
+
if (this.options.leading && this.store.state.canLeadingExecute) {
|
|
53
|
+
this.#setState({ canLeadingExecute: false });
|
|
54
|
+
_didLeadingExecute = true;
|
|
55
|
+
this.#execute(...args);
|
|
56
|
+
}
|
|
57
|
+
if (this.options.trailing) {
|
|
58
|
+
this.#setState({ isPending: true, lastArgs: args });
|
|
59
|
+
}
|
|
60
|
+
if (this.#timeoutId) clearTimeout(this.#timeoutId);
|
|
61
|
+
this.#timeoutId = setTimeout(() => {
|
|
62
|
+
this.#setState({ canLeadingExecute: true });
|
|
63
|
+
if (this.options.trailing && !_didLeadingExecute) {
|
|
64
|
+
this.#execute(...args);
|
|
65
|
+
}
|
|
66
|
+
}, this.#getWait());
|
|
67
|
+
};
|
|
68
|
+
this.#execute = (...args) => {
|
|
69
|
+
if (!this.#getEnabled()) return void 0;
|
|
70
|
+
this.fn(...args);
|
|
71
|
+
this.#setState({
|
|
72
|
+
isPending: false,
|
|
73
|
+
executionCount: this.store.state.executionCount + 1
|
|
74
|
+
});
|
|
75
|
+
this.options.onExecute?.(this);
|
|
76
|
+
};
|
|
77
|
+
this.flush = () => {
|
|
78
|
+
if (this.store.state.isPending && this.store.state.lastArgs) {
|
|
79
|
+
this.#clearTimeout();
|
|
80
|
+
this.#execute(...this.store.state.lastArgs);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
this.#clearTimeout = () => {
|
|
84
|
+
if (this.#timeoutId) {
|
|
85
|
+
clearTimeout(this.#timeoutId);
|
|
86
|
+
this.#timeoutId = void 0;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
this.cancel = () => {
|
|
90
|
+
this.#clearTimeout();
|
|
91
|
+
this.#setState({
|
|
92
|
+
canLeadingExecute: true,
|
|
93
|
+
isPending: false
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
this.reset = () => {
|
|
97
|
+
this.#setState(getDefaultDebouncerState());
|
|
98
|
+
};
|
|
99
|
+
this.options = {
|
|
17
100
|
...defaultOptions,
|
|
18
101
|
...initialOptions
|
|
19
102
|
};
|
|
103
|
+
this.#setState(this.options.initialState ?? {});
|
|
20
104
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
this._isPending = false;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Returns the current debouncer options
|
|
32
|
-
*/
|
|
33
|
-
getOptions() {
|
|
34
|
-
return this._options;
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* Returns the current enabled state of the debouncer
|
|
38
|
-
*/
|
|
39
|
-
getEnabled() {
|
|
40
|
-
return parseFunctionOrValue(this._options.enabled, this);
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Returns the current wait time in milliseconds
|
|
44
|
-
*/
|
|
45
|
-
getWait() {
|
|
46
|
-
return parseFunctionOrValue(this._options.wait, this);
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Attempts to execute the debounced function
|
|
50
|
-
* If a call is already in progress, it will be queued
|
|
51
|
-
*/
|
|
52
|
-
maybeExecute(...args) {
|
|
53
|
-
let _didLeadingExecute = false;
|
|
54
|
-
if (this._options.leading && this._canLeadingExecute) {
|
|
55
|
-
this._canLeadingExecute = false;
|
|
56
|
-
_didLeadingExecute = true;
|
|
57
|
-
this.execute(...args);
|
|
58
|
-
}
|
|
59
|
-
if (this._options.trailing) {
|
|
60
|
-
this._isPending = true;
|
|
61
|
-
}
|
|
62
|
-
if (this._timeoutId) clearTimeout(this._timeoutId);
|
|
63
|
-
this._timeoutId = setTimeout(() => {
|
|
64
|
-
this._canLeadingExecute = true;
|
|
65
|
-
if (this._options.trailing && !_didLeadingExecute) {
|
|
66
|
-
this.execute(...args);
|
|
67
|
-
}
|
|
68
|
-
}, this.getWait());
|
|
69
|
-
}
|
|
70
|
-
execute(...args) {
|
|
71
|
-
if (!this.getEnabled()) return void 0;
|
|
72
|
-
this.fn(...args);
|
|
73
|
-
this._isPending = false;
|
|
74
|
-
this._executionCount++;
|
|
75
|
-
this._options.onExecute(this);
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* Cancels any pending execution
|
|
79
|
-
*/
|
|
80
|
-
cancel() {
|
|
81
|
-
if (this._timeoutId) {
|
|
82
|
-
clearTimeout(this._timeoutId);
|
|
83
|
-
this._canLeadingExecute = true;
|
|
84
|
-
this._isPending = false;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Returns the number of times the function has been executed
|
|
89
|
-
*/
|
|
90
|
-
getExecutionCount() {
|
|
91
|
-
return this._executionCount;
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Returns `true` if debouncing
|
|
95
|
-
*/
|
|
96
|
-
getIsPending() {
|
|
97
|
-
return this.getEnabled() && this._isPending;
|
|
98
|
-
}
|
|
105
|
+
#timeoutId;
|
|
106
|
+
#setState;
|
|
107
|
+
#getEnabled;
|
|
108
|
+
#getWait;
|
|
109
|
+
#execute;
|
|
110
|
+
#clearTimeout;
|
|
99
111
|
}
|
|
100
112
|
function debounce(fn, initialOptions) {
|
|
101
113
|
const debouncer = new Debouncer(fn, initialOptions);
|
|
102
|
-
return debouncer.maybeExecute
|
|
114
|
+
return debouncer.maybeExecute;
|
|
103
115
|
}
|
|
104
116
|
export {
|
|
105
117
|
Debouncer,
|