@tanstack/pacer 0.7.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 +123 -102
- 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 +105 -84
- 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 +123 -102
- 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 +105 -84
- 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 +341 -220
- package/src/async-rate-limiter.ts +176 -136
- package/src/async-throttler.ts +233 -139
- package/src/batcher.ts +159 -93
- package/src/debouncer.ts +135 -52
- package/src/index.ts +1 -1
- package/src/queuer.ts +349 -227
- 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/cjs/batcher.d.cts
CHANGED
|
@@ -1,3 +1,39 @@
|
|
|
1
|
+
import { Store } from '@tanstack/store';
|
|
2
|
+
import { OptionalKeys } from './types.cjs';
|
|
3
|
+
export interface BatcherState<TValue> {
|
|
4
|
+
/**
|
|
5
|
+
* Number of batch executions that have been completed
|
|
6
|
+
*/
|
|
7
|
+
executionCount: number;
|
|
8
|
+
/**
|
|
9
|
+
* Whether the batcher has no items to process (items array is empty)
|
|
10
|
+
*/
|
|
11
|
+
isEmpty: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Whether the batcher is waiting for the timeout to trigger batch processing
|
|
14
|
+
*/
|
|
15
|
+
isPending: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Whether the batcher is active and will process items automatically
|
|
18
|
+
*/
|
|
19
|
+
isRunning: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Total number of items that have been processed across all batches
|
|
22
|
+
*/
|
|
23
|
+
totalItemsProcessed: number;
|
|
24
|
+
/**
|
|
25
|
+
* Array of items currently queued for batch processing
|
|
26
|
+
*/
|
|
27
|
+
items: Array<TValue>;
|
|
28
|
+
/**
|
|
29
|
+
* Number of items currently in the batch queue
|
|
30
|
+
*/
|
|
31
|
+
size: number;
|
|
32
|
+
/**
|
|
33
|
+
* Current processing status - 'idle' when not processing, 'pending' when waiting for timeout
|
|
34
|
+
*/
|
|
35
|
+
status: 'idle' | 'pending';
|
|
36
|
+
}
|
|
1
37
|
/**
|
|
2
38
|
* Options for configuring a Batcher instance
|
|
3
39
|
*/
|
|
@@ -7,6 +43,10 @@ export interface BatcherOptions<TValue> {
|
|
|
7
43
|
* Return true to process the batch immediately
|
|
8
44
|
*/
|
|
9
45
|
getShouldExecute?: (items: Array<TValue>, batcher: Batcher<TValue>) => boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Initial state for the batcher
|
|
48
|
+
*/
|
|
49
|
+
initialState?: Partial<BatcherState<TValue>>;
|
|
10
50
|
/**
|
|
11
51
|
* Maximum number of items in a batch
|
|
12
52
|
* @default Infinity
|
|
@@ -16,10 +56,6 @@ export interface BatcherOptions<TValue> {
|
|
|
16
56
|
* Callback fired after a batch is processed
|
|
17
57
|
*/
|
|
18
58
|
onExecute?: (batcher: Batcher<TValue>) => void;
|
|
19
|
-
/**
|
|
20
|
-
* Callback fired when the batcher's running state changes
|
|
21
|
-
*/
|
|
22
|
-
onIsRunningChange?: (batcher: Batcher<TValue>) => void;
|
|
23
59
|
/**
|
|
24
60
|
* Callback fired after items are added to the batcher
|
|
25
61
|
*/
|
|
@@ -35,8 +71,9 @@ export interface BatcherOptions<TValue> {
|
|
|
35
71
|
* If not provided, the batch will not be triggered by a timeout.
|
|
36
72
|
* @default Infinity
|
|
37
73
|
*/
|
|
38
|
-
wait?: number;
|
|
74
|
+
wait?: number | ((batcher: Batcher<TValue>) => number);
|
|
39
75
|
}
|
|
76
|
+
type BatcherOptionsWithOptionalCallbacks<TValue> = OptionalKeys<Required<BatcherOptions<TValue>>, 'initialState' | 'onExecute' | 'onItemsChange'>;
|
|
40
77
|
/**
|
|
41
78
|
* A class that collects items and processes them in batches.
|
|
42
79
|
*
|
|
@@ -48,6 +85,15 @@ export interface BatcherOptions<TValue> {
|
|
|
48
85
|
* - Custom batch processing logic via getShouldExecute
|
|
49
86
|
* - Event callbacks for monitoring batch operations
|
|
50
87
|
*
|
|
88
|
+
* State Management:
|
|
89
|
+
* - Uses TanStack Store for reactive state management
|
|
90
|
+
* - Use `initialState` to provide initial state values when creating the batcher
|
|
91
|
+
* - Use `onExecute` callback to react to batch execution and implement custom logic
|
|
92
|
+
* - Use `onItemsChange` callback to react to items being added or removed from the batcher
|
|
93
|
+
* - The state includes batch execution count, total items processed, items, and running status
|
|
94
|
+
* - State can be accessed via `batcher.store.state` when using the class directly
|
|
95
|
+
* - When using framework adapters (React/Solid), state is accessed from `batcher.state`
|
|
96
|
+
*
|
|
51
97
|
* @example
|
|
52
98
|
* ```ts
|
|
53
99
|
* const batcher = new Batcher<number>(
|
|
@@ -55,7 +101,7 @@ export interface BatcherOptions<TValue> {
|
|
|
55
101
|
* {
|
|
56
102
|
* maxSize: 5,
|
|
57
103
|
* wait: 2000,
|
|
58
|
-
*
|
|
104
|
+
* onExecute: (batcher) => console.log('Batch executed:', batcher.peekAllItems())
|
|
59
105
|
* }
|
|
60
106
|
* );
|
|
61
107
|
*
|
|
@@ -63,83 +109,61 @@ export interface BatcherOptions<TValue> {
|
|
|
63
109
|
* batcher.addItem(2);
|
|
64
110
|
* // After 2 seconds or when 5 items are added, whichever comes first,
|
|
65
111
|
* // the batch will be processed
|
|
66
|
-
* // batcher.
|
|
112
|
+
* // batcher.flush() // manually trigger a batch
|
|
67
113
|
* ```
|
|
68
114
|
*/
|
|
69
115
|
export declare class Batcher<TValue> {
|
|
116
|
+
#private;
|
|
70
117
|
private fn;
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
private _itemExecutionCount;
|
|
74
|
-
private _items;
|
|
75
|
-
private _running;
|
|
76
|
-
private _timeoutId;
|
|
118
|
+
readonly store: Store<Readonly<BatcherState<TValue>>>;
|
|
119
|
+
options: BatcherOptionsWithOptionalCallbacks<TValue>;
|
|
77
120
|
constructor(fn: (items: Array<TValue>) => void, initialOptions: BatcherOptions<TValue>);
|
|
78
121
|
/**
|
|
79
122
|
* Updates the batcher options
|
|
80
123
|
*/
|
|
81
|
-
setOptions(newOptions: Partial<BatcherOptions<TValue>>)
|
|
82
|
-
/**
|
|
83
|
-
* Returns the current batcher options
|
|
84
|
-
*/
|
|
85
|
-
getOptions(): BatcherOptions<TValue>;
|
|
124
|
+
setOptions: (newOptions: Partial<BatcherOptions<TValue>>) => void;
|
|
86
125
|
/**
|
|
87
126
|
* Adds an item to the batcher
|
|
88
127
|
* If the batch size is reached, timeout occurs, or shouldProcess returns true, the batch will be processed
|
|
89
128
|
*/
|
|
90
|
-
addItem(item: TValue)
|
|
129
|
+
addItem: (item: TValue) => void;
|
|
91
130
|
/**
|
|
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.
|
|
131
|
+
* Processes the current batch of items immediately
|
|
99
132
|
*/
|
|
100
|
-
|
|
133
|
+
flush: () => void;
|
|
101
134
|
/**
|
|
102
135
|
* Stops the batcher from processing batches
|
|
103
136
|
*/
|
|
104
|
-
stop()
|
|
137
|
+
stop: () => void;
|
|
105
138
|
/**
|
|
106
139
|
* Starts the batcher and processes any pending items
|
|
107
140
|
*/
|
|
108
|
-
start()
|
|
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;
|
|
141
|
+
start: () => void;
|
|
121
142
|
/**
|
|
122
|
-
* Returns a copy of all items
|
|
143
|
+
* Returns a copy of all items in the batcher
|
|
123
144
|
*/
|
|
124
|
-
|
|
145
|
+
peekAllItems: () => Array<TValue>;
|
|
125
146
|
/**
|
|
126
|
-
*
|
|
147
|
+
* Removes all items from the batcher
|
|
127
148
|
*/
|
|
128
|
-
|
|
149
|
+
clear: () => void;
|
|
129
150
|
/**
|
|
130
|
-
*
|
|
151
|
+
* Resets the batcher state to its default values
|
|
131
152
|
*/
|
|
132
|
-
|
|
153
|
+
reset: () => void;
|
|
133
154
|
}
|
|
134
155
|
/**
|
|
135
156
|
* Creates a batcher that processes items in batches
|
|
136
157
|
*
|
|
137
158
|
* @example
|
|
138
159
|
* ```ts
|
|
139
|
-
* const batchItems = batch<number>(
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
160
|
+
* const batchItems = batch<number>(
|
|
161
|
+
* (items) => console.log('Processing:', items),
|
|
162
|
+
* {
|
|
163
|
+
* maxSize: 3,
|
|
164
|
+
* onExecute: (batcher) => console.log('Batch executed')
|
|
165
|
+
* }
|
|
166
|
+
* );
|
|
143
167
|
*
|
|
144
168
|
* batchItems(1);
|
|
145
169
|
* batchItems(2);
|
|
@@ -147,3 +171,4 @@ export declare class Batcher<TValue> {
|
|
|
147
171
|
* ```
|
|
148
172
|
*/
|
|
149
173
|
export declare function batch<TValue>(fn: (items: Array<TValue>) => void, options: BatcherOptions<TValue>): (item: TValue) => void;
|
|
174
|
+
export {};
|
package/dist/cjs/debouncer.cjs
CHANGED
|
@@ -1,107 +1,119 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const store = require("@tanstack/store");
|
|
3
4
|
const utils = require("./utils.cjs");
|
|
5
|
+
function getDefaultDebouncerState() {
|
|
6
|
+
return structuredClone({
|
|
7
|
+
canLeadingExecute: true,
|
|
8
|
+
executionCount: 0,
|
|
9
|
+
isPending: false,
|
|
10
|
+
lastArgs: void 0,
|
|
11
|
+
status: "idle"
|
|
12
|
+
});
|
|
13
|
+
}
|
|
4
14
|
const defaultOptions = {
|
|
5
15
|
enabled: true,
|
|
6
16
|
leading: false,
|
|
7
|
-
onExecute: () => {
|
|
8
|
-
},
|
|
9
17
|
trailing: true,
|
|
10
18
|
wait: 0
|
|
11
19
|
};
|
|
12
20
|
class Debouncer {
|
|
13
21
|
constructor(fn, initialOptions) {
|
|
14
22
|
this.fn = fn;
|
|
15
|
-
this.
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
this.
|
|
23
|
+
this.store = new store.Store(
|
|
24
|
+
getDefaultDebouncerState()
|
|
25
|
+
);
|
|
26
|
+
this.setOptions = (newOptions) => {
|
|
27
|
+
this.options = { ...this.options, ...newOptions };
|
|
28
|
+
if (!this.#getEnabled()) {
|
|
29
|
+
this.cancel();
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
this.#setState = (newState) => {
|
|
33
|
+
this.store.setState((state) => {
|
|
34
|
+
const combinedState = {
|
|
35
|
+
...state,
|
|
36
|
+
...newState
|
|
37
|
+
};
|
|
38
|
+
const { isPending } = combinedState;
|
|
39
|
+
return {
|
|
40
|
+
...combinedState,
|
|
41
|
+
status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
|
|
42
|
+
};
|
|
43
|
+
});
|
|
44
|
+
};
|
|
45
|
+
this.#getEnabled = () => {
|
|
46
|
+
return !!utils.parseFunctionOrValue(this.options.enabled, this);
|
|
47
|
+
};
|
|
48
|
+
this.#getWait = () => {
|
|
49
|
+
return utils.parseFunctionOrValue(this.options.wait, this);
|
|
50
|
+
};
|
|
51
|
+
this.maybeExecute = (...args) => {
|
|
52
|
+
if (!this.#getEnabled()) return void 0;
|
|
53
|
+
let _didLeadingExecute = false;
|
|
54
|
+
if (this.options.leading && this.store.state.canLeadingExecute) {
|
|
55
|
+
this.#setState({ canLeadingExecute: false });
|
|
56
|
+
_didLeadingExecute = true;
|
|
57
|
+
this.#execute(...args);
|
|
58
|
+
}
|
|
59
|
+
if (this.options.trailing) {
|
|
60
|
+
this.#setState({ isPending: true, lastArgs: args });
|
|
61
|
+
}
|
|
62
|
+
if (this.#timeoutId) clearTimeout(this.#timeoutId);
|
|
63
|
+
this.#timeoutId = setTimeout(() => {
|
|
64
|
+
this.#setState({ canLeadingExecute: true });
|
|
65
|
+
if (this.options.trailing && !_didLeadingExecute) {
|
|
66
|
+
this.#execute(...args);
|
|
67
|
+
}
|
|
68
|
+
}, this.#getWait());
|
|
69
|
+
};
|
|
70
|
+
this.#execute = (...args) => {
|
|
71
|
+
if (!this.#getEnabled()) return void 0;
|
|
72
|
+
this.fn(...args);
|
|
73
|
+
this.#setState({
|
|
74
|
+
isPending: false,
|
|
75
|
+
executionCount: this.store.state.executionCount + 1
|
|
76
|
+
});
|
|
77
|
+
this.options.onExecute?.(this);
|
|
78
|
+
};
|
|
79
|
+
this.flush = () => {
|
|
80
|
+
if (this.store.state.isPending && this.store.state.lastArgs) {
|
|
81
|
+
this.#clearTimeout();
|
|
82
|
+
this.#execute(...this.store.state.lastArgs);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
this.#clearTimeout = () => {
|
|
86
|
+
if (this.#timeoutId) {
|
|
87
|
+
clearTimeout(this.#timeoutId);
|
|
88
|
+
this.#timeoutId = void 0;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
this.cancel = () => {
|
|
92
|
+
this.#clearTimeout();
|
|
93
|
+
this.#setState({
|
|
94
|
+
canLeadingExecute: true,
|
|
95
|
+
isPending: false
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
this.reset = () => {
|
|
99
|
+
this.#setState(getDefaultDebouncerState());
|
|
100
|
+
};
|
|
101
|
+
this.options = {
|
|
19
102
|
...defaultOptions,
|
|
20
103
|
...initialOptions
|
|
21
104
|
};
|
|
105
|
+
this.#setState(this.options.initialState ?? {});
|
|
22
106
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
this._isPending = false;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Returns the current debouncer options
|
|
34
|
-
*/
|
|
35
|
-
getOptions() {
|
|
36
|
-
return this._options;
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Returns the current enabled state of the debouncer
|
|
40
|
-
*/
|
|
41
|
-
getEnabled() {
|
|
42
|
-
return utils.parseFunctionOrValue(this._options.enabled, this);
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Returns the current wait time in milliseconds
|
|
46
|
-
*/
|
|
47
|
-
getWait() {
|
|
48
|
-
return utils.parseFunctionOrValue(this._options.wait, this);
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Attempts to execute the debounced function
|
|
52
|
-
* If a call is already in progress, it will be queued
|
|
53
|
-
*/
|
|
54
|
-
maybeExecute(...args) {
|
|
55
|
-
let _didLeadingExecute = false;
|
|
56
|
-
if (this._options.leading && this._canLeadingExecute) {
|
|
57
|
-
this._canLeadingExecute = false;
|
|
58
|
-
_didLeadingExecute = true;
|
|
59
|
-
this.execute(...args);
|
|
60
|
-
}
|
|
61
|
-
if (this._options.trailing) {
|
|
62
|
-
this._isPending = true;
|
|
63
|
-
}
|
|
64
|
-
if (this._timeoutId) clearTimeout(this._timeoutId);
|
|
65
|
-
this._timeoutId = setTimeout(() => {
|
|
66
|
-
this._canLeadingExecute = true;
|
|
67
|
-
if (this._options.trailing && !_didLeadingExecute) {
|
|
68
|
-
this.execute(...args);
|
|
69
|
-
}
|
|
70
|
-
}, this.getWait());
|
|
71
|
-
}
|
|
72
|
-
execute(...args) {
|
|
73
|
-
if (!this.getEnabled()) return void 0;
|
|
74
|
-
this.fn(...args);
|
|
75
|
-
this._isPending = false;
|
|
76
|
-
this._executionCount++;
|
|
77
|
-
this._options.onExecute(this);
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Cancels any pending execution
|
|
81
|
-
*/
|
|
82
|
-
cancel() {
|
|
83
|
-
if (this._timeoutId) {
|
|
84
|
-
clearTimeout(this._timeoutId);
|
|
85
|
-
this._canLeadingExecute = true;
|
|
86
|
-
this._isPending = false;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Returns the number of times the function has been executed
|
|
91
|
-
*/
|
|
92
|
-
getExecutionCount() {
|
|
93
|
-
return this._executionCount;
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Returns `true` if debouncing
|
|
97
|
-
*/
|
|
98
|
-
getIsPending() {
|
|
99
|
-
return this.getEnabled() && this._isPending;
|
|
100
|
-
}
|
|
107
|
+
#timeoutId;
|
|
108
|
+
#setState;
|
|
109
|
+
#getEnabled;
|
|
110
|
+
#getWait;
|
|
111
|
+
#execute;
|
|
112
|
+
#clearTimeout;
|
|
101
113
|
}
|
|
102
114
|
function debounce(fn, initialOptions) {
|
|
103
115
|
const debouncer = new Debouncer(fn, initialOptions);
|
|
104
|
-
return debouncer.maybeExecute
|
|
116
|
+
return debouncer.maybeExecute;
|
|
105
117
|
}
|
|
106
118
|
exports.Debouncer = Debouncer;
|
|
107
119
|
exports.debounce = debounce;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"debouncer.cjs","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":["parseFunctionOrValue"],"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,kBA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AM9B,SAAe;AACb,QAAI,KAAK,YAAY;AACnB,mBAAa,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;;;"}
|
|
1
|
+
{"version":3,"file":"debouncer.cjs","sources":["../../src/debouncer.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\nexport interface DebouncerState<TFn extends AnyFunction> {\n /**\n * Whether the debouncer can execute on the leading edge of the timeout\n */\n canLeadingExecute: boolean\n /**\n * Number of function executions that have been completed\n */\n executionCount: number\n /**\n * Whether the debouncer is waiting for the timeout to trigger execution\n */\n isPending: boolean\n /**\n * The arguments from the most recent call to maybeExecute\n */\n lastArgs: Parameters<TFn> | undefined\n /**\n * Current execution status - 'idle' when not active, 'pending' when waiting for timeout\n */\n status: 'disabled' | 'idle' | 'pending'\n}\n\nfunction getDefaultDebouncerState<\n TFn extends AnyFunction,\n>(): DebouncerState<TFn> {\n return structuredClone({\n canLeadingExecute: true,\n executionCount: 0,\n isPending: false,\n lastArgs: undefined,\n status: 'idle',\n })\n}\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 * Initial state for the debouncer\n */\n initialState?: Partial<DebouncerState<TFn>>\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: Omit<\n Required<DebouncerOptions<any>>,\n 'initialState' | 'onExecute'\n> = {\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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via `debouncer.store.state` when using the class directly\n * - When using framework adapters (React/Solid), state is accessed from `debouncer.state`\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 readonly store: Store<Readonly<DebouncerState<TFn>>> = new Store(\n getDefaultDebouncerState<TFn>(),\n )\n options: DebouncerOptions<TFn>\n #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 this.#setState(this.options.initialState ?? {})\n }\n\n /**\n * Updates the debouncer options\n */\n setOptions = (newOptions: Partial<DebouncerOptions<TFn>>): void => {\n this.options = { ...this.options, ...newOptions }\n\n // Cancel pending execution if the debouncer is disabled\n if (!this.#getEnabled()) {\n this.cancel()\n }\n }\n\n #setState = (newState: Partial<DebouncerState<TFn>>): void => {\n this.store.setState((state) => {\n const combinedState = {\n ...state,\n ...newState,\n }\n const { isPending } = combinedState\n return {\n ...combinedState,\n status: !this.#getEnabled()\n ? 'disabled'\n : isPending\n ? 'pending'\n : 'idle',\n }\n })\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 if (!this.#getEnabled()) return undefined\n let _didLeadingExecute = false\n\n // Handle leading execution\n if (this.options.leading && this.store.state.canLeadingExecute) {\n this.#setState({ 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.#setState({ isPending: true, lastArgs: args })\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.#setState({ canLeadingExecute: true })\n if (this.options.trailing && !_didLeadingExecute) {\n this.#execute(...args)\n }\n }, this.#getWait())\n }\n\n #execute = (...args: Parameters<TFn>): void => {\n if (!this.#getEnabled()) return undefined\n this.fn(...args) // EXECUTE!\n this.#setState({\n isPending: false,\n executionCount: this.store.state.executionCount + 1,\n })\n this.options.onExecute?.(this)\n }\n\n /**\n * Processes the current pending execution immediately\n */\n flush = (): void => {\n if (this.store.state.isPending && this.store.state.lastArgs) {\n this.#clearTimeout() // clear any pending timeout\n this.#execute(...this.store.state.lastArgs) // execute immediately\n }\n }\n\n #clearTimeout = (): void => {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId)\n this.#timeoutId = undefined\n }\n }\n\n /**\n * Cancels any pending execution\n */\n cancel = (): void => {\n this.#clearTimeout()\n this.#setState({\n canLeadingExecute: true,\n isPending: false,\n })\n }\n\n /**\n * Resets the debouncer state to its default values\n */\n reset = (): void => {\n this.#setState(getDefaultDebouncerState<TFn>())\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 * State Management:\n * - Uses TanStack Store for reactive state management\n * - Use `initialState` to provide initial state values when creating the debouncer\n * - Use `onExecute` callback to react to function execution and implement custom logic\n * - The state includes canLeadingExecute, execution count, and isPending status\n * - State can be accessed via the underlying Debouncer instance's `store.state` property\n * - When using framework adapters (React/Solid), state is accessed from the hook's state property\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\n}\n"],"names":["Store","parseFunctionOrValue"],"mappings":";;;;AA2BA,SAAS,2BAEgB;AACvB,SAAO,gBAAgB;AAAA,IACrB,mBAAmB;AAAA,IACnB,gBAAgB;AAAA,IAChB,WAAW;AAAA,IACX,UAAU;AAAA,IACV,QAAQ;AAAA,EAAA,CACT;AACH;AAuCA,MAAM,iBAGF;AAAA,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SAAO,UAAU;AACnB;;;"}
|
package/dist/cjs/debouncer.d.cts
CHANGED
|
@@ -1,4 +1,27 @@
|
|
|
1
|
+
import { Store } from '@tanstack/store';
|
|
1
2
|
import { AnyFunction } from './types.cjs';
|
|
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/cjs/index.cjs
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const asyncBatcher = require("./async-batcher.cjs");
|
|
3
4
|
const asyncDebouncer = require("./async-debouncer.cjs");
|
|
4
5
|
const asyncQueuer = require("./async-queuer.cjs");
|
|
5
6
|
const asyncRateLimiter = require("./async-rate-limiter.cjs");
|
|
6
7
|
const asyncThrottler = require("./async-throttler.cjs");
|
|
7
8
|
const batcher = require("./batcher.cjs");
|
|
8
|
-
const compare = require("./compare.cjs");
|
|
9
9
|
const debouncer = require("./debouncer.cjs");
|
|
10
10
|
const queuer = require("./queuer.cjs");
|
|
11
11
|
const rateLimiter = require("./rate-limiter.cjs");
|
|
12
12
|
const throttler = require("./throttler.cjs");
|
|
13
13
|
const utils = require("./utils.cjs");
|
|
14
|
+
exports.AsyncBatcher = asyncBatcher.AsyncBatcher;
|
|
15
|
+
exports.asyncBatch = asyncBatcher.asyncBatch;
|
|
14
16
|
exports.AsyncDebouncer = asyncDebouncer.AsyncDebouncer;
|
|
15
17
|
exports.asyncDebounce = asyncDebouncer.asyncDebounce;
|
|
16
18
|
exports.AsyncQueuer = asyncQueuer.AsyncQueuer;
|
|
@@ -21,10 +23,6 @@ exports.AsyncThrottler = asyncThrottler.AsyncThrottler;
|
|
|
21
23
|
exports.asyncThrottle = asyncThrottler.asyncThrottle;
|
|
22
24
|
exports.Batcher = batcher.Batcher;
|
|
23
25
|
exports.batch = batcher.batch;
|
|
24
|
-
exports.isPlainArray = compare.isPlainArray;
|
|
25
|
-
exports.isPlainObject = compare.isPlainObject;
|
|
26
|
-
exports.replaceEqualDeep = compare.replaceEqualDeep;
|
|
27
|
-
exports.shallowEqualObjects = compare.shallowEqualObjects;
|
|
28
26
|
exports.Debouncer = debouncer.Debouncer;
|
|
29
27
|
exports.debounce = debouncer.debounce;
|
|
30
28
|
exports.Queuer = queuer.Queuer;
|
|
@@ -33,7 +31,6 @@ exports.RateLimiter = rateLimiter.RateLimiter;
|
|
|
33
31
|
exports.rateLimit = rateLimiter.rateLimit;
|
|
34
32
|
exports.Throttler = throttler.Throttler;
|
|
35
33
|
exports.throttle = throttler.throttle;
|
|
36
|
-
exports.bindInstanceMethods = utils.bindInstanceMethods;
|
|
37
34
|
exports.isFunction = utils.isFunction;
|
|
38
35
|
exports.parseFunctionOrValue = utils.parseFunctionOrValue;
|
|
39
36
|
//# sourceMappingURL=index.cjs.map
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/cjs/index.d.cts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
export * from './async-batcher.cjs';
|
|
1
2
|
export * from './async-debouncer.cjs';
|
|
2
3
|
export * from './async-queuer.cjs';
|
|
3
4
|
export * from './async-rate-limiter.cjs';
|
|
4
5
|
export * from './async-throttler.cjs';
|
|
5
6
|
export * from './batcher.cjs';
|
|
6
|
-
export * from './compare.cjs';
|
|
7
7
|
export * from './debouncer.cjs';
|
|
8
8
|
export * from './queuer.cjs';
|
|
9
9
|
export * from './rate-limiter.cjs';
|