@tanstack/pacer 0.5.0 → 0.7.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-debouncer.cjs +32 -17
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +51 -9
- package/dist/cjs/async-queuer.cjs +189 -191
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +151 -94
- package/dist/cjs/async-rate-limiter.cjs +23 -13
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +54 -5
- package/dist/cjs/async-throttler.cjs +38 -17
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +51 -8
- package/dist/cjs/batcher.cjs +138 -0
- package/dist/cjs/batcher.cjs.map +1 -0
- package/dist/cjs/batcher.d.cts +149 -0
- package/dist/cjs/debouncer.cjs +3 -4
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +1 -2
- package/dist/cjs/index.cjs +3 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +1 -0
- package/dist/cjs/queuer.cjs +68 -41
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +123 -92
- package/dist/cjs/rate-limiter.cjs +3 -4
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +1 -2
- package/dist/cjs/throttler.cjs +3 -4
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +1 -2
- package/dist/cjs/types.d.cts +1 -0
- package/dist/esm/async-debouncer.d.ts +51 -9
- package/dist/esm/async-debouncer.js +32 -17
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +151 -94
- package/dist/esm/async-queuer.js +189 -191
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +54 -5
- package/dist/esm/async-rate-limiter.js +23 -13
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +51 -8
- package/dist/esm/async-throttler.js +38 -17
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/batcher.d.ts +149 -0
- package/dist/esm/batcher.js +138 -0
- package/dist/esm/batcher.js.map +1 -0
- package/dist/esm/debouncer.d.ts +1 -2
- package/dist/esm/debouncer.js +3 -4
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +3 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/queuer.d.ts +123 -92
- package/dist/esm/queuer.js +68 -41
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +1 -2
- package/dist/esm/rate-limiter.js +3 -4
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +1 -2
- package/dist/esm/throttler.js +3 -4
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/types.d.ts +1 -0
- package/package.json +11 -1
- package/src/async-debouncer.ts +76 -20
- package/src/async-queuer.ts +309 -275
- package/src/async-rate-limiter.ts +73 -16
- package/src/async-throttler.ts +84 -20
- package/src/batcher.ts +253 -0
- package/src/debouncer.ts +3 -4
- package/src/index.ts +1 -0
- package/src/queuer.ts +142 -98
- package/src/rate-limiter.ts +3 -4
- package/src/throttler.ts +3 -4
- package/src/types.ts +3 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for configuring a Batcher instance
|
|
3
|
+
*/
|
|
4
|
+
export interface BatcherOptions<TValue> {
|
|
5
|
+
/**
|
|
6
|
+
* Custom function to determine if a batch should be processed
|
|
7
|
+
* Return true to process the batch immediately
|
|
8
|
+
*/
|
|
9
|
+
getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Maximum number of items in a batch
|
|
12
|
+
* @default Infinity
|
|
13
|
+
*/
|
|
14
|
+
maxSize?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Callback fired after a batch is processed
|
|
17
|
+
*/
|
|
18
|
+
onExecute?: (batcher: Batcher<TValue>) => void;
|
|
19
|
+
/**
|
|
20
|
+
* Callback fired when the batcher's running state changes
|
|
21
|
+
*/
|
|
22
|
+
onIsRunningChange?: (batcher: Batcher<TValue>) => void;
|
|
23
|
+
/**
|
|
24
|
+
* Callback fired after items are added to the batcher
|
|
25
|
+
*/
|
|
26
|
+
onItemsChange?: (batcher: Batcher<TValue>) => void;
|
|
27
|
+
/**
|
|
28
|
+
* Whether the batcher should start processing immediately
|
|
29
|
+
* @default true
|
|
30
|
+
*/
|
|
31
|
+
started?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Maximum time in milliseconds to wait before processing a batch.
|
|
34
|
+
* If the wait duration has elapsed, the batch will be processed.
|
|
35
|
+
* If not provided, the batch will not be triggered by a timeout.
|
|
36
|
+
* @default Infinity
|
|
37
|
+
*/
|
|
38
|
+
wait?: number;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* A class that collects items and processes them in batches.
|
|
42
|
+
*
|
|
43
|
+
* Batching is a technique for grouping multiple operations together to be processed as a single unit.
|
|
44
|
+
*
|
|
45
|
+
* The Batcher provides a flexible way to implement batching with configurable:
|
|
46
|
+
* - Maximum batch size (number of items per batch)
|
|
47
|
+
* - Time-based batching (process after X milliseconds)
|
|
48
|
+
* - Custom batch processing logic via getShouldExecute
|
|
49
|
+
* - Event callbacks for monitoring batch operations
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* const batcher = new Batcher<number>(
|
|
54
|
+
* (items) => console.log('Processing batch:', items),
|
|
55
|
+
* {
|
|
56
|
+
* maxSize: 5,
|
|
57
|
+
* wait: 2000,
|
|
58
|
+
* onExecuteBatch: (items) => console.log('Batch executed:', items)
|
|
59
|
+
* }
|
|
60
|
+
* );
|
|
61
|
+
*
|
|
62
|
+
* batcher.addItem(1);
|
|
63
|
+
* batcher.addItem(2);
|
|
64
|
+
* // After 2 seconds or when 5 items are added, whichever comes first,
|
|
65
|
+
* // the batch will be processed
|
|
66
|
+
* // batcher.execute() // manually trigger a batch
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export declare class Batcher<TValue> {
|
|
70
|
+
private fn;
|
|
71
|
+
private _options;
|
|
72
|
+
private _batchExecutionCount;
|
|
73
|
+
private _itemExecutionCount;
|
|
74
|
+
private _items;
|
|
75
|
+
private _running;
|
|
76
|
+
private _timeoutId;
|
|
77
|
+
constructor(fn: (items: Array<TValue>) => void, initialOptions: BatcherOptions<TValue>);
|
|
78
|
+
/**
|
|
79
|
+
* Updates the batcher options
|
|
80
|
+
*/
|
|
81
|
+
setOptions(newOptions: Partial<BatcherOptions<TValue>>): void;
|
|
82
|
+
/**
|
|
83
|
+
* Returns the current batcher options
|
|
84
|
+
*/
|
|
85
|
+
getOptions(): BatcherOptions<TValue>;
|
|
86
|
+
/**
|
|
87
|
+
* Adds an item to the batcher
|
|
88
|
+
* If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
|
|
89
|
+
*/
|
|
90
|
+
addItem(item: TValue): void;
|
|
91
|
+
/**
|
|
92
|
+
* Processes the current batch of items.
|
|
93
|
+
* This method will automatically be triggered if the batcher is running and any of these conditions are met:
|
|
94
|
+
* - The number of items reaches batchSize
|
|
95
|
+
* - The wait duration has elapsed
|
|
96
|
+
* - The getShouldExecute function returns true upon adding an item
|
|
97
|
+
*
|
|
98
|
+
* You can also call this method manually to process the current batch at any time.
|
|
99
|
+
*/
|
|
100
|
+
execute(): void;
|
|
101
|
+
/**
|
|
102
|
+
* Stops the batcher from processing batches
|
|
103
|
+
*/
|
|
104
|
+
stop(): void;
|
|
105
|
+
/**
|
|
106
|
+
* Starts the batcher and processes any pending items
|
|
107
|
+
*/
|
|
108
|
+
start(): void;
|
|
109
|
+
/**
|
|
110
|
+
* Returns the current number of items in the batcher
|
|
111
|
+
*/
|
|
112
|
+
getSize(): number;
|
|
113
|
+
/**
|
|
114
|
+
* Returns true if the batcher is empty
|
|
115
|
+
*/
|
|
116
|
+
getIsEmpty(): boolean;
|
|
117
|
+
/**
|
|
118
|
+
* Returns true if the batcher is running
|
|
119
|
+
*/
|
|
120
|
+
getIsRunning(): boolean;
|
|
121
|
+
/**
|
|
122
|
+
* Returns a copy of all items currently in the batcher
|
|
123
|
+
*/
|
|
124
|
+
getAllItems(): Array<TValue>;
|
|
125
|
+
/**
|
|
126
|
+
* Returns the number of times batches have been processed
|
|
127
|
+
*/
|
|
128
|
+
getBatchExecutionCount(): number;
|
|
129
|
+
/**
|
|
130
|
+
* Returns the total number of individual items that have been processed
|
|
131
|
+
*/
|
|
132
|
+
getItemExecutionCount(): number;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Creates a batcher that processes items in batches
|
|
136
|
+
*
|
|
137
|
+
* @example
|
|
138
|
+
* ```ts
|
|
139
|
+
* const batchItems = batch<number>({
|
|
140
|
+
* batchSize: 3,
|
|
141
|
+
* processBatch: (items) => console.log('Processing:', items)
|
|
142
|
+
* });
|
|
143
|
+
*
|
|
144
|
+
* batchItems(1);
|
|
145
|
+
* batchItems(2);
|
|
146
|
+
* batchItems(3); // Triggers batch processing
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
export declare function batch<TValue>(fn: (items: Array<TValue>) => void, options: BatcherOptions<TValue>): (item: TValue) => void;
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
const defaultOptions = {
|
|
2
|
+
getShouldExecute: () => false,
|
|
3
|
+
maxSize: Infinity,
|
|
4
|
+
started: true,
|
|
5
|
+
wait: Infinity
|
|
6
|
+
};
|
|
7
|
+
class Batcher {
|
|
8
|
+
constructor(fn, initialOptions) {
|
|
9
|
+
this.fn = fn;
|
|
10
|
+
this._batchExecutionCount = 0;
|
|
11
|
+
this._itemExecutionCount = 0;
|
|
12
|
+
this._items = [];
|
|
13
|
+
this._timeoutId = null;
|
|
14
|
+
this._options = { ...defaultOptions, ...initialOptions };
|
|
15
|
+
this._running = this._options.started;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Updates the batcher options
|
|
19
|
+
*/
|
|
20
|
+
setOptions(newOptions) {
|
|
21
|
+
this._options = { ...this._options, ...newOptions };
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Returns the current batcher options
|
|
25
|
+
*/
|
|
26
|
+
getOptions() {
|
|
27
|
+
return this._options;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Adds an item to the batcher
|
|
31
|
+
* If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
|
|
32
|
+
*/
|
|
33
|
+
addItem(item) {
|
|
34
|
+
var _a, _b;
|
|
35
|
+
this._items.push(item);
|
|
36
|
+
(_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
|
|
37
|
+
const shouldProcess = this._items.length >= this._options.maxSize || this._options.getShouldExecute(this._items, this);
|
|
38
|
+
if (shouldProcess) {
|
|
39
|
+
this.execute();
|
|
40
|
+
} else if (this._running && !this._timeoutId && this._options.wait !== Infinity) {
|
|
41
|
+
this._timeoutId = setTimeout(() => this.execute(), this._options.wait);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Processes the current batch of items.
|
|
46
|
+
* This method will automatically be triggered if the batcher is running and any of these conditions are met:
|
|
47
|
+
* - The number of items reaches batchSize
|
|
48
|
+
* - The wait duration has elapsed
|
|
49
|
+
* - The getShouldExecute function returns true upon adding an item
|
|
50
|
+
*
|
|
51
|
+
* You can also call this method manually to process the current batch at any time.
|
|
52
|
+
*/
|
|
53
|
+
execute() {
|
|
54
|
+
var _a, _b, _c, _d;
|
|
55
|
+
if (this._timeoutId) {
|
|
56
|
+
clearTimeout(this._timeoutId);
|
|
57
|
+
this._timeoutId = null;
|
|
58
|
+
}
|
|
59
|
+
if (this._items.length === 0) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const batch2 = this.getAllItems();
|
|
63
|
+
this._items = [];
|
|
64
|
+
(_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
|
|
65
|
+
this.fn(batch2);
|
|
66
|
+
this._batchExecutionCount++;
|
|
67
|
+
this._itemExecutionCount += batch2.length;
|
|
68
|
+
(_d = (_c = this._options).onExecute) == null ? void 0 : _d.call(_c, this);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Stops the batcher from processing batches
|
|
72
|
+
*/
|
|
73
|
+
stop() {
|
|
74
|
+
var _a, _b;
|
|
75
|
+
this._running = false;
|
|
76
|
+
(_b = (_a = this._options).onIsRunningChange) == null ? void 0 : _b.call(_a, this);
|
|
77
|
+
if (this._timeoutId) {
|
|
78
|
+
clearTimeout(this._timeoutId);
|
|
79
|
+
this._timeoutId = null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Starts the batcher and processes any pending items
|
|
84
|
+
*/
|
|
85
|
+
start() {
|
|
86
|
+
var _a, _b;
|
|
87
|
+
this._running = true;
|
|
88
|
+
(_b = (_a = this._options).onIsRunningChange) == null ? void 0 : _b.call(_a, this);
|
|
89
|
+
if (this._items.length > 0 && !this._timeoutId) {
|
|
90
|
+
this._timeoutId = setTimeout(() => this.execute(), this._options.wait);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Returns the current number of items in the batcher
|
|
95
|
+
*/
|
|
96
|
+
getSize() {
|
|
97
|
+
return this._items.length;
|
|
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
|
+
getAllItems() {
|
|
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;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function batch(fn, options) {
|
|
131
|
+
const batcher = new Batcher(fn, options);
|
|
132
|
+
return batcher.addItem.bind(batcher);
|
|
133
|
+
}
|
|
134
|
+
export {
|
|
135
|
+
Batcher,
|
|
136
|
+
batch
|
|
137
|
+
};
|
|
138
|
+
//# sourceMappingURL=batcher.js.map
|
|
@@ -0,0 +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.getAllItems() // 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 getAllItems(): 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":"AA+CA,MAAM,iBAA2D;AAAA,EAC/D,kBAAkB,MAAM;AAAA,EACxB,SAAS;AAAA,EACT,SAAS;AAAA,EACT,MAAM;AACR;AA+BO,MAAM,QAAgB;AAAA,EAQ3B,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAQ,uBAAuB;AAC/B,SAAQ,sBAAsB;AAC9B,SAAQ,SAAwB,CAAC;AAEjC,SAAQ,aAAoC;AAM1C,SAAK,WAAW,EAAE,GAAG,gBAAgB,GAAG,eAAe;AAClD,SAAA,WAAW,KAAK,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMhC,WAAW,YAAmD;AAC5D,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMpD,aAAqC;AACnC,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,QAAQ,MAAoB;AAtE9B;AAuES,SAAA,OAAO,KAAK,IAAI;AAChB,qBAAA,UAAS,kBAAT,4BAAyB;AAE9B,UAAM,gBACJ,KAAK,OAAO,UAAU,KAAK,SAAS,WACpC,KAAK,SAAS,iBAAiB,KAAK,QAAQ,IAAI;AAElD,QAAI,eAAe;AACjB,WAAK,QAAQ;AAAA,IAAA,WAEb,KAAK,YACL,CAAC,KAAK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AAC,GAAG,KAAK,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMxB,yBAAiC;AAC/B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,wBAAgC;AAC9B,WAAO,KAAK;AAAA,EAAA;AAEhB;AAiBgB,SAAA,MACd,IACA,SACA;AACA,QAAM,UAAU,IAAI,QAAgB,IAAI,OAAO;AACxC,SAAA,QAAQ,QAAQ,KAAK,OAAO;AACrC;"}
|
package/dist/esm/debouncer.d.ts
CHANGED
|
@@ -64,7 +64,6 @@ export declare class Debouncer<TFn extends AnyFunction> {
|
|
|
64
64
|
constructor(fn: TFn, initialOptions: DebouncerOptions<TFn>);
|
|
65
65
|
/**
|
|
66
66
|
* Updates the debouncer options
|
|
67
|
-
* Returns the new options state
|
|
68
67
|
*/
|
|
69
68
|
setOptions(newOptions: Partial<DebouncerOptions<TFn>>): void;
|
|
70
69
|
/**
|
|
@@ -84,7 +83,7 @@ export declare class Debouncer<TFn extends AnyFunction> {
|
|
|
84
83
|
* If a call is already in progress, it will be queued
|
|
85
84
|
*/
|
|
86
85
|
maybeExecute(...args: Parameters<TFn>): void;
|
|
87
|
-
private
|
|
86
|
+
private execute;
|
|
88
87
|
/**
|
|
89
88
|
* Cancels any pending execution
|
|
90
89
|
*/
|
package/dist/esm/debouncer.js
CHANGED
|
@@ -20,7 +20,6 @@ class Debouncer {
|
|
|
20
20
|
}
|
|
21
21
|
/**
|
|
22
22
|
* Updates the debouncer options
|
|
23
|
-
* Returns the new options state
|
|
24
23
|
*/
|
|
25
24
|
setOptions(newOptions) {
|
|
26
25
|
this._options = { ...this._options, ...newOptions };
|
|
@@ -55,7 +54,7 @@ class Debouncer {
|
|
|
55
54
|
if (this._options.leading && this._canLeadingExecute) {
|
|
56
55
|
this._canLeadingExecute = false;
|
|
57
56
|
_didLeadingExecute = true;
|
|
58
|
-
this.
|
|
57
|
+
this.execute(...args);
|
|
59
58
|
}
|
|
60
59
|
if (this._options.trailing) {
|
|
61
60
|
this._isPending = true;
|
|
@@ -64,11 +63,11 @@ class Debouncer {
|
|
|
64
63
|
this._timeoutId = setTimeout(() => {
|
|
65
64
|
this._canLeadingExecute = true;
|
|
66
65
|
if (this._options.trailing && !_didLeadingExecute) {
|
|
67
|
-
this.
|
|
66
|
+
this.execute(...args);
|
|
68
67
|
}
|
|
69
68
|
}, this.getWait());
|
|
70
69
|
}
|
|
71
|
-
|
|
70
|
+
execute(...args) {
|
|
72
71
|
if (!this.getEnabled()) return void 0;
|
|
73
72
|
this.fn(...args);
|
|
74
73
|
this._isPending = false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debouncer.js","sources":["../../src/debouncer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Whether to execute on the leading edge of the timeout.\n * The first call will execute immediately and the rest will wait the delay.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (debouncer: Debouncer<TFn>) => void\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 * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\nconst defaultOptions: Required<DebouncerOptions<any>> = {\n enabled: true,\n leading: false,\n onExecute: () => {},\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<TFn extends AnyFunction> {\n private _canLeadingExecute = true\n private _executionCount = 0\n private _isPending = false\n private _options: Required<DebouncerOptions<TFn>>\n private _timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n
|
|
1
|
+
{"version":3,"file":"debouncer.js","sources":["../../src/debouncer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\n/**\n * Options for configuring a debounced function\n */\nexport interface DebouncerOptions<TFn extends AnyFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: Debouncer<TFn>) => boolean)\n /**\n * Whether to execute on the leading edge of the timeout.\n * The first call will execute immediately and the rest will wait the delay.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (debouncer: Debouncer<TFn>) => void\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 * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: Debouncer<TFn>) => number)\n}\n\nconst defaultOptions: Required<DebouncerOptions<any>> = {\n enabled: true,\n leading: false,\n onExecute: () => {},\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<TFn extends AnyFunction> {\n private _canLeadingExecute = true\n private _executionCount = 0\n private _isPending = false\n private _options: Required<DebouncerOptions<TFn>>\n private _timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions(newOptions: Partial<DebouncerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<DebouncerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Returns the current enabled state of the debouncer\n */\n getEnabled(): boolean {\n return parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\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: Parameters<TFn>): void {\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n _didLeadingExecute = true\n this.execute(...args)\n }\n\n // Start pending state to indicate that the debouncer is waiting for the trailing edge\n if (this._options.trailing) {\n this._isPending = true\n }\n\n // Clear any existing timeout\n if (this._timeoutId) clearTimeout(this._timeoutId)\n\n // Set new timeout that will reset canLeadingExecute and execute trailing only if enabled and did not execute leading\n this._timeoutId = setTimeout(() => {\n this._canLeadingExecute = true\n if (this._options.trailing && !_didLeadingExecute) {\n this.execute(...args)\n }\n }, this.getWait())\n }\n\n private execute(...args: Parameters<TFn>): void {\n if (!this.getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this._isPending = false\n this._executionCount++\n this._options.onExecute(this)\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 this._isPending = false\n }\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 * Returns `true` if debouncing\n */\n getIsPending(): boolean {\n return this.getEnabled() && this._isPending\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 AnyFunction>(\n fn: TFn,\n initialOptions: DebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new Debouncer(fn, initialOptions)\n return debouncer.maybeExecute.bind(debouncer)\n}\n"],"names":[],"mappings":";AAoCA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AAyBO,MAAM,UAAmC;AAAA,EAO9C,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAQ,qBAAqB;AAC7B,SAAQ,kBAAkB;AAC1B,SAAQ,aAAa;AAQnB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a,KAAK,UAAU;AAC5B,WAAK,qBAAqB;AAC1B,WAAK,aAAa;AAAA,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAMF,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,gBAAgB,KAAK;AAAA,EAAA;AAErC;AAsBgB,SAAA,SACd,IACA,gBACoC;AACpC,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export * from './async-debouncer.js';
|
|
|
2
2
|
export * from './async-queuer.js';
|
|
3
3
|
export * from './async-rate-limiter.js';
|
|
4
4
|
export * from './async-throttler.js';
|
|
5
|
+
export * from './batcher.js';
|
|
5
6
|
export * from './compare.js';
|
|
6
7
|
export * from './debouncer.js';
|
|
7
8
|
export * from './queuer.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import { AsyncDebouncer, asyncDebounce } from "./async-debouncer.js";
|
|
|
2
2
|
import { AsyncQueuer, asyncQueue } from "./async-queuer.js";
|
|
3
3
|
import { AsyncRateLimiter, asyncRateLimit } from "./async-rate-limiter.js";
|
|
4
4
|
import { AsyncThrottler, asyncThrottle } from "./async-throttler.js";
|
|
5
|
+
import { Batcher, batch } from "./batcher.js";
|
|
5
6
|
import { isPlainArray, isPlainObject, replaceEqualDeep, shallowEqualObjects } from "./compare.js";
|
|
6
7
|
import { Debouncer, debounce } from "./debouncer.js";
|
|
7
8
|
import { Queuer, queue } from "./queuer.js";
|
|
@@ -13,6 +14,7 @@ export {
|
|
|
13
14
|
AsyncQueuer,
|
|
14
15
|
AsyncRateLimiter,
|
|
15
16
|
AsyncThrottler,
|
|
17
|
+
Batcher,
|
|
16
18
|
Debouncer,
|
|
17
19
|
Queuer,
|
|
18
20
|
RateLimiter,
|
|
@@ -21,6 +23,7 @@ export {
|
|
|
21
23
|
asyncQueue,
|
|
22
24
|
asyncRateLimit,
|
|
23
25
|
asyncThrottle,
|
|
26
|
+
batch,
|
|
24
27
|
bindInstanceMethods,
|
|
25
28
|
debounce,
|
|
26
29
|
isFunction,
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;"}
|