@tanstack/pacer 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/cjs/async-debouncer.cjs +109 -0
- package/dist/cjs/async-debouncer.cjs.map +1 -0
- package/dist/cjs/async-debouncer.d.cts +99 -0
- package/dist/cjs/async-queuer.cjs +293 -0
- package/dist/cjs/async-queuer.cjs.map +1 -0
- package/dist/cjs/async-queuer.d.cts +197 -0
- package/dist/cjs/async-rate-limiter.cjs +122 -0
- package/dist/cjs/async-rate-limiter.cjs.map +1 -0
- package/dist/cjs/async-rate-limiter.d.cts +132 -0
- package/dist/cjs/async-throttler.cjs +115 -0
- package/dist/cjs/async-throttler.cjs.map +1 -0
- package/dist/cjs/async-throttler.d.cts +93 -0
- package/dist/cjs/compare.cjs +72 -0
- package/dist/cjs/compare.cjs.map +1 -0
- package/dist/cjs/compare.d.cts +12 -0
- package/dist/cjs/debouncer.cjs +74 -0
- package/dist/cjs/debouncer.cjs.map +1 -0
- package/dist/cjs/debouncer.d.cts +96 -0
- package/dist/cjs/index.cjs +32 -0
- package/dist/cjs/index.cjs.map +1 -0
- package/dist/cjs/index.d.cts +9 -0
- package/dist/cjs/queuer.cjs +231 -0
- package/dist/cjs/queuer.cjs.map +1 -0
- package/dist/cjs/queuer.d.cts +221 -0
- package/dist/cjs/rate-limiter.cjs +115 -0
- package/dist/cjs/rate-limiter.cjs.map +1 -0
- package/dist/cjs/rate-limiter.d.cts +147 -0
- package/dist/cjs/throttler.cjs +120 -0
- package/dist/cjs/throttler.cjs.map +1 -0
- package/dist/cjs/throttler.d.cts +139 -0
- package/dist/esm/async-debouncer.d.ts +99 -0
- package/dist/esm/async-debouncer.js +109 -0
- package/dist/esm/async-debouncer.js.map +1 -0
- package/dist/esm/async-queuer.d.ts +197 -0
- package/dist/esm/async-queuer.js +293 -0
- package/dist/esm/async-queuer.js.map +1 -0
- package/dist/esm/async-rate-limiter.d.ts +132 -0
- package/dist/esm/async-rate-limiter.js +122 -0
- package/dist/esm/async-rate-limiter.js.map +1 -0
- package/dist/esm/async-throttler.d.ts +93 -0
- package/dist/esm/async-throttler.js +115 -0
- package/dist/esm/async-throttler.js.map +1 -0
- package/dist/esm/compare.d.ts +12 -0
- package/dist/esm/compare.js +72 -0
- package/dist/esm/compare.js.map +1 -0
- package/dist/esm/debouncer.d.ts +96 -0
- package/dist/esm/debouncer.js +74 -0
- package/dist/esm/debouncer.js.map +1 -0
- package/dist/esm/index.d.ts +9 -0
- package/dist/esm/index.js +32 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/queuer.d.ts +221 -0
- package/dist/esm/queuer.js +231 -0
- package/dist/esm/queuer.js.map +1 -0
- package/dist/esm/rate-limiter.d.ts +147 -0
- package/dist/esm/rate-limiter.js +115 -0
- package/dist/esm/rate-limiter.js.map +1 -0
- package/dist/esm/throttler.d.ts +139 -0
- package/dist/esm/throttler.js +120 -0
- package/dist/esm/throttler.js.map +1 -0
- package/package.json +150 -0
- package/src/async-debouncer.ts +197 -0
- package/src/async-queuer.ts +447 -0
- package/src/async-rate-limiter.ts +228 -0
- package/src/async-throttler.ts +194 -0
- package/src/compare.ts +105 -0
- package/src/debouncer.ts +164 -0
- package/src/index.ts +9 -0
- package/src/queuer.ts +394 -0
- package/src/rate-limiter.ts +236 -0
- package/src/throttler.ts +222 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for configuring an async debounced function
|
|
3
|
+
*/
|
|
4
|
+
export interface AsyncDebouncerOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
7
|
+
* Defaults to true.
|
|
8
|
+
*/
|
|
9
|
+
enabled?: boolean
|
|
10
|
+
/**
|
|
11
|
+
* Whether to execute on the leading edge of the timeout.
|
|
12
|
+
* Defaults to false.
|
|
13
|
+
*/
|
|
14
|
+
leading?: boolean
|
|
15
|
+
/**
|
|
16
|
+
* Whether to execute on the trailing edge of the timeout.
|
|
17
|
+
* Defaults to true.
|
|
18
|
+
*/
|
|
19
|
+
trailing?: boolean
|
|
20
|
+
/**
|
|
21
|
+
* Delay in milliseconds to wait after the last call before executing
|
|
22
|
+
* Defaults to 0ms
|
|
23
|
+
*/
|
|
24
|
+
wait: number
|
|
25
|
+
/**
|
|
26
|
+
* Optional error handler for when the debounced function throws
|
|
27
|
+
*/
|
|
28
|
+
onError?: (error: unknown) => void
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const defaultOptions: Required<AsyncDebouncerOptions> = {
|
|
32
|
+
enabled: true,
|
|
33
|
+
leading: false,
|
|
34
|
+
trailing: true,
|
|
35
|
+
onError: () => {},
|
|
36
|
+
wait: 0,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A class that creates an async debounced function.
|
|
41
|
+
*
|
|
42
|
+
* Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
|
|
43
|
+
* Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
|
|
44
|
+
* or input changes where you only want to execute the handler after the events have stopped occurring.
|
|
45
|
+
*
|
|
46
|
+
* Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
|
|
47
|
+
* the function stops being called for the specified delay period.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```ts
|
|
51
|
+
* const debouncer = new AsyncDebouncer(async (value: string) => {
|
|
52
|
+
* await searchAPI(value);
|
|
53
|
+
* }, { wait: 500 });
|
|
54
|
+
*
|
|
55
|
+
* // Called on each keystroke but only executes after 500ms of no typing
|
|
56
|
+
* inputElement.addEventListener('input', () => {
|
|
57
|
+
* debouncer.maybeExecute(inputElement.value);
|
|
58
|
+
* });
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
export class AsyncDebouncer<
|
|
62
|
+
TFn extends (...args: Array<any>) => Promise<any>,
|
|
63
|
+
TArgs extends Parameters<TFn>,
|
|
64
|
+
> {
|
|
65
|
+
private abortController: AbortController | null = null
|
|
66
|
+
private executionCount = 0
|
|
67
|
+
private isExecuting = false
|
|
68
|
+
private lastArgs: TArgs | undefined
|
|
69
|
+
private options: Required<AsyncDebouncerOptions>
|
|
70
|
+
private timeoutId: ReturnType<typeof setTimeout> | null = null
|
|
71
|
+
private canLeadingExecute = true
|
|
72
|
+
|
|
73
|
+
constructor(
|
|
74
|
+
private fn: TFn,
|
|
75
|
+
initialOptions: AsyncDebouncerOptions,
|
|
76
|
+
) {
|
|
77
|
+
this.options = {
|
|
78
|
+
...defaultOptions,
|
|
79
|
+
...initialOptions,
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Updates the debouncer options
|
|
85
|
+
* Returns the new options state
|
|
86
|
+
*/
|
|
87
|
+
setOptions(
|
|
88
|
+
newOptions: Partial<AsyncDebouncerOptions>,
|
|
89
|
+
): Required<AsyncDebouncerOptions> {
|
|
90
|
+
this.options = {
|
|
91
|
+
...this.options,
|
|
92
|
+
...newOptions,
|
|
93
|
+
}
|
|
94
|
+
return this.options
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Returns the number of times the function has been executed
|
|
99
|
+
*/
|
|
100
|
+
getExecutionCount(): number {
|
|
101
|
+
return this.executionCount
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Cancels any pending execution
|
|
106
|
+
*/
|
|
107
|
+
cancel(): void {
|
|
108
|
+
if (this.timeoutId) {
|
|
109
|
+
clearTimeout(this.timeoutId)
|
|
110
|
+
this.timeoutId = null
|
|
111
|
+
}
|
|
112
|
+
if (this.abortController) {
|
|
113
|
+
this.abortController.abort()
|
|
114
|
+
this.abortController = null
|
|
115
|
+
}
|
|
116
|
+
this.lastArgs = undefined
|
|
117
|
+
this.canLeadingExecute = true
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Attempts to execute the debounced function
|
|
122
|
+
* If a call is already in progress, it will be queued
|
|
123
|
+
*/
|
|
124
|
+
async maybeExecute(...args: TArgs): Promise<void> {
|
|
125
|
+
this.cancel()
|
|
126
|
+
this.lastArgs = args
|
|
127
|
+
|
|
128
|
+
// Handle leading execution
|
|
129
|
+
if (this.options.leading && this.canLeadingExecute) {
|
|
130
|
+
this.canLeadingExecute = false
|
|
131
|
+
await this.executeFunction(...args)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return new Promise((resolve) => {
|
|
135
|
+
this.timeoutId = setTimeout(async () => {
|
|
136
|
+
if (this.isExecuting) {
|
|
137
|
+
resolve()
|
|
138
|
+
return
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
this.canLeadingExecute = true
|
|
142
|
+
// Execute trailing only if enabled
|
|
143
|
+
if (this.options.trailing) {
|
|
144
|
+
this.abortController = new AbortController()
|
|
145
|
+
try {
|
|
146
|
+
this.isExecuting = true
|
|
147
|
+
if (this.lastArgs) {
|
|
148
|
+
await this.executeFunction(...this.lastArgs)
|
|
149
|
+
}
|
|
150
|
+
} catch (error) {
|
|
151
|
+
try {
|
|
152
|
+
this.options.onError(error)
|
|
153
|
+
} catch {
|
|
154
|
+
// Ignore errors from error handler
|
|
155
|
+
}
|
|
156
|
+
} finally {
|
|
157
|
+
this.isExecuting = false
|
|
158
|
+
this.abortController = null
|
|
159
|
+
resolve()
|
|
160
|
+
}
|
|
161
|
+
} else {
|
|
162
|
+
resolve()
|
|
163
|
+
}
|
|
164
|
+
}, this.options.wait)
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private async executeFunction(...args: TArgs): Promise<void> {
|
|
169
|
+
if (!this.options.enabled) return
|
|
170
|
+
this.executionCount++
|
|
171
|
+
await this.fn(...args)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Creates an async debounced function that delays execution until after a specified wait time.
|
|
177
|
+
* The debounced function will only execute once the wait period has elapsed without any new calls.
|
|
178
|
+
* If called again during the wait period, the timer resets and a new wait period begins.
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* ```ts
|
|
182
|
+
* const debounced = asyncDebounce(async (value: string) => {
|
|
183
|
+
* await saveToAPI(value);
|
|
184
|
+
* }, { wait: 1000 });
|
|
185
|
+
*
|
|
186
|
+
* // Will only execute once, 1 second after the last call
|
|
187
|
+
* await debounced("first"); // Cancelled
|
|
188
|
+
* await debounced("second"); // Cancelled
|
|
189
|
+
* await debounced("third"); // Executes after 1s
|
|
190
|
+
* ```
|
|
191
|
+
*/
|
|
192
|
+
export function asyncDebounce<
|
|
193
|
+
TFn extends (...args: Array<any>) => Promise<any>,
|
|
194
|
+
>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions, 'enabled'>) {
|
|
195
|
+
const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)
|
|
196
|
+
return asyncDebouncer.maybeExecute.bind(asyncDebouncer)
|
|
197
|
+
}
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import type { QueuePosition } from './queuer'
|
|
2
|
+
|
|
3
|
+
export interface AsyncQueuerOptions<TValue> {
|
|
4
|
+
/**
|
|
5
|
+
* Default position to add items to the queuer
|
|
6
|
+
* @default 'back'
|
|
7
|
+
*/
|
|
8
|
+
addItemsTo?: QueuePosition
|
|
9
|
+
/**
|
|
10
|
+
* Maximum number of concurrent tasks to process
|
|
11
|
+
*/
|
|
12
|
+
concurrency?: number
|
|
13
|
+
/**
|
|
14
|
+
* Default position to get items from during processing
|
|
15
|
+
* @default 'front'
|
|
16
|
+
*/
|
|
17
|
+
getItemsFrom?: QueuePosition
|
|
18
|
+
/**
|
|
19
|
+
* Function to determine priority of items in the queuer
|
|
20
|
+
* Higher priority items will be processed first
|
|
21
|
+
* If not provided, will use static priority values attached to tasks
|
|
22
|
+
*/
|
|
23
|
+
getPriority?: (item: () => Promise<TValue>) => number
|
|
24
|
+
/**
|
|
25
|
+
* Initial items to populate the queuer with
|
|
26
|
+
*/
|
|
27
|
+
initialItems?: Array<(() => Promise<TValue>) & { priority?: number }>
|
|
28
|
+
/**
|
|
29
|
+
* Maximum number of items allowed in the queuer
|
|
30
|
+
*/
|
|
31
|
+
maxSize?: number
|
|
32
|
+
/**
|
|
33
|
+
* Callback fired whenever an item is removed from the queuer
|
|
34
|
+
*/
|
|
35
|
+
onGetNextItem?: (
|
|
36
|
+
item: () => Promise<TValue>,
|
|
37
|
+
queuer: AsyncQueuer<TValue>,
|
|
38
|
+
) => void
|
|
39
|
+
/**
|
|
40
|
+
* Callback fired whenever an item is added or removed from the queuer
|
|
41
|
+
*/
|
|
42
|
+
onUpdate?: (queuer: AsyncQueuer<TValue>) => void
|
|
43
|
+
/**
|
|
44
|
+
* Whether the queuer should start processing tasks immediately
|
|
45
|
+
*/
|
|
46
|
+
started?: boolean
|
|
47
|
+
/**
|
|
48
|
+
* Time in milliseconds to wait between processing items
|
|
49
|
+
*/
|
|
50
|
+
wait?: number
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const defaultOptions: Required<AsyncQueuerOptions<any>> = {
|
|
54
|
+
addItemsTo: 'back',
|
|
55
|
+
concurrency: 1,
|
|
56
|
+
getItemsFrom: 'front',
|
|
57
|
+
getPriority: (item) => (item as any).priority ?? 0,
|
|
58
|
+
initialItems: [],
|
|
59
|
+
maxSize: Infinity,
|
|
60
|
+
onGetNextItem: () => {},
|
|
61
|
+
onUpdate: () => {},
|
|
62
|
+
started: false,
|
|
63
|
+
wait: 0,
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* A flexible asynchronous queuer that processes tasks with configurable concurrency control.
|
|
68
|
+
*
|
|
69
|
+
* Features:
|
|
70
|
+
* - Priority queuer support via getPriority option
|
|
71
|
+
* - Configurable concurrency limit
|
|
72
|
+
* - Task success/error/completion callbacks
|
|
73
|
+
* - FIFO (First In First Out) or LIFO (Last In First Out) queuer behavior
|
|
74
|
+
* - Pause/resume task processing
|
|
75
|
+
* - Task cancellation
|
|
76
|
+
*
|
|
77
|
+
* Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
|
|
78
|
+
* the next pending task is processed if below the concurrency limit.
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* ```ts
|
|
82
|
+
* const queuer = new AsyncQueuer<string>({ concurrency: 2 });
|
|
83
|
+
*
|
|
84
|
+
* queuer.addItem(async () => {
|
|
85
|
+
* return 'Hello';
|
|
86
|
+
* });
|
|
87
|
+
*
|
|
88
|
+
* queuer.start();
|
|
89
|
+
*
|
|
90
|
+
* queuer.onSuccess((result) => {
|
|
91
|
+
* console.log(result); // 'Hello'
|
|
92
|
+
* });
|
|
93
|
+
* ```
|
|
94
|
+
*/
|
|
95
|
+
export class AsyncQueuer<TValue> {
|
|
96
|
+
protected options: Required<AsyncQueuerOptions<TValue>>
|
|
97
|
+
private items: Array<() => Promise<TValue>> = []
|
|
98
|
+
private activeItems: Set<() => Promise<TValue>> = new Set()
|
|
99
|
+
private onSuccessCallbacks: Array<(result: TValue) => void> = []
|
|
100
|
+
private onErrorCallbacks: Array<(error: Error) => void> = []
|
|
101
|
+
private onSettledCallbacks: Array<(result: TValue | Error) => void> = []
|
|
102
|
+
private running: boolean
|
|
103
|
+
private pendingTick = false
|
|
104
|
+
private executionCount = 0
|
|
105
|
+
|
|
106
|
+
constructor(initialOptions: AsyncQueuerOptions<TValue> = defaultOptions) {
|
|
107
|
+
this.options = { ...defaultOptions, ...initialOptions }
|
|
108
|
+
this.running = this.options.started
|
|
109
|
+
|
|
110
|
+
for (let i = 0; i < this.options.initialItems.length; i++) {
|
|
111
|
+
const item = this.options.initialItems[i]!
|
|
112
|
+
const isLast = i === this.options.initialItems.length - 1
|
|
113
|
+
this.addItem(item, this.options.addItemsTo, isLast)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Updates the queuer options
|
|
119
|
+
* Returns the new options state
|
|
120
|
+
*/
|
|
121
|
+
setOptions(
|
|
122
|
+
newOptions: Partial<AsyncQueuerOptions<TValue>>,
|
|
123
|
+
): AsyncQueuerOptions<TValue> {
|
|
124
|
+
this.options = { ...this.options, ...newOptions }
|
|
125
|
+
return this.options
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Processes items in the queuer
|
|
130
|
+
*/
|
|
131
|
+
protected tick() {
|
|
132
|
+
if (!this.running) {
|
|
133
|
+
this.pendingTick = false
|
|
134
|
+
return
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
while (
|
|
138
|
+
this.activeItems.size < this.options.concurrency &&
|
|
139
|
+
!this.isEmpty()
|
|
140
|
+
) {
|
|
141
|
+
const nextFn = this.getNextItem()
|
|
142
|
+
if (!nextFn) {
|
|
143
|
+
break
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
this.activeItems.add(nextFn)
|
|
147
|
+
;(async () => {
|
|
148
|
+
let success = false
|
|
149
|
+
let res!: TValue
|
|
150
|
+
let error: Error | undefined
|
|
151
|
+
|
|
152
|
+
try {
|
|
153
|
+
res = await nextFn()
|
|
154
|
+
success = true
|
|
155
|
+
} catch (e) {
|
|
156
|
+
error = e as Error
|
|
157
|
+
} finally {
|
|
158
|
+
this.options.onUpdate(this)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
this.activeItems.delete(nextFn)
|
|
162
|
+
if (success) {
|
|
163
|
+
this.onSuccessCallbacks.forEach((cb) => cb(res))
|
|
164
|
+
} else {
|
|
165
|
+
this.onErrorCallbacks.forEach((cb) => cb(error!))
|
|
166
|
+
}
|
|
167
|
+
this.onSettledCallbacks.forEach((cb) => cb(success ? res : error!))
|
|
168
|
+
|
|
169
|
+
if (this.options.wait > 0) {
|
|
170
|
+
setTimeout(() => this.tick(), this.options.wait)
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
this.tick()
|
|
175
|
+
})()
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
this.pendingTick = false
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Adds a task to the queuer
|
|
183
|
+
*/
|
|
184
|
+
addItem(
|
|
185
|
+
fn: (() => Promise<TValue>) & { priority?: number },
|
|
186
|
+
position: QueuePosition = this.options.addItemsTo,
|
|
187
|
+
runOnUpdate: boolean = true,
|
|
188
|
+
): Promise<TValue> {
|
|
189
|
+
if (this.isFull()) {
|
|
190
|
+
return Promise.reject(new Error('Queuer is full'))
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return new Promise<TValue>((resolve, reject) => {
|
|
194
|
+
const task = Object.assign(
|
|
195
|
+
async () => {
|
|
196
|
+
try {
|
|
197
|
+
const result = await fn()
|
|
198
|
+
resolve(result)
|
|
199
|
+
return result
|
|
200
|
+
} catch (error) {
|
|
201
|
+
reject(error)
|
|
202
|
+
throw error
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
{ priority: fn.priority ?? undefined },
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
// Get priority either from the function or from getPriority option
|
|
209
|
+
const priority =
|
|
210
|
+
this.options.getPriority !== defaultOptions.getPriority
|
|
211
|
+
? this.options.getPriority(task)
|
|
212
|
+
: task.priority
|
|
213
|
+
|
|
214
|
+
if (priority !== undefined) {
|
|
215
|
+
// Insert based on priority
|
|
216
|
+
const insertIndex = this.items.findIndex((existing) => {
|
|
217
|
+
const existingPriority =
|
|
218
|
+
this.options.getPriority !== defaultOptions.getPriority
|
|
219
|
+
? this.options.getPriority(existing)
|
|
220
|
+
: (existing as any).priority
|
|
221
|
+
return existingPriority > priority
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
if (insertIndex === -1) {
|
|
225
|
+
this.items.push(task)
|
|
226
|
+
} else {
|
|
227
|
+
this.items.splice(insertIndex, 0, task)
|
|
228
|
+
}
|
|
229
|
+
} else {
|
|
230
|
+
// Default FIFO/LIFO behavior
|
|
231
|
+
if (position === 'front') {
|
|
232
|
+
this.items.unshift(task)
|
|
233
|
+
} else {
|
|
234
|
+
this.items.push(task)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (runOnUpdate) {
|
|
239
|
+
this.options.onUpdate(this)
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (this.running && !this.pendingTick) {
|
|
243
|
+
this.pendingTick = true
|
|
244
|
+
this.tick()
|
|
245
|
+
}
|
|
246
|
+
})
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Removes and returns an item from the queuer
|
|
251
|
+
*/
|
|
252
|
+
getNextItem(
|
|
253
|
+
position: QueuePosition = this.options.getItemsFrom,
|
|
254
|
+
): (() => Promise<TValue>) | undefined {
|
|
255
|
+
let item: (() => Promise<TValue>) | undefined
|
|
256
|
+
|
|
257
|
+
if (position === 'front') {
|
|
258
|
+
item = this.items.shift()
|
|
259
|
+
} else {
|
|
260
|
+
item = this.items.pop()
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (item !== undefined) {
|
|
264
|
+
this.executionCount++
|
|
265
|
+
this.options.onUpdate(this)
|
|
266
|
+
this.options.onGetNextItem(item, this)
|
|
267
|
+
}
|
|
268
|
+
return item
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Returns an item without removing it
|
|
273
|
+
*/
|
|
274
|
+
peek(position: QueuePosition = 'front'): (() => Promise<TValue>) | undefined {
|
|
275
|
+
if (position === 'front') {
|
|
276
|
+
return this.items[0]
|
|
277
|
+
}
|
|
278
|
+
return this.items[this.items.length - 1]
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Returns true if the queuer is empty
|
|
283
|
+
*/
|
|
284
|
+
isEmpty(): boolean {
|
|
285
|
+
return this.items.length === 0
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Returns true if the queuer is full
|
|
290
|
+
*/
|
|
291
|
+
isFull(): boolean {
|
|
292
|
+
return this.items.length >= this.options.maxSize
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Returns the current size of the queuer
|
|
297
|
+
*/
|
|
298
|
+
size(): number {
|
|
299
|
+
return this.items.length
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Removes all items from the queuer
|
|
304
|
+
*/
|
|
305
|
+
clear(): void {
|
|
306
|
+
this.items = []
|
|
307
|
+
this.options.onUpdate(this)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Resets the queuer to its initial state
|
|
312
|
+
*/
|
|
313
|
+
reset(withInitialItems?: boolean): void {
|
|
314
|
+
this.clear()
|
|
315
|
+
this.executionCount = 0
|
|
316
|
+
if (withInitialItems) {
|
|
317
|
+
this.items = [...this.options.initialItems]
|
|
318
|
+
}
|
|
319
|
+
this.running = this.options.started
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Returns a copy of all items in the queuer
|
|
324
|
+
*/
|
|
325
|
+
getAllItems(): Array<() => Promise<TValue>> {
|
|
326
|
+
return [...this.items]
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Returns the number of items that have been removed from the queuer
|
|
331
|
+
*/
|
|
332
|
+
getExecutionCount(): number {
|
|
333
|
+
return this.executionCount
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Returns the active items
|
|
338
|
+
*/
|
|
339
|
+
getActiveItems(): Array<() => Promise<TValue>> {
|
|
340
|
+
return Array.from(this.activeItems)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Returns the pending items
|
|
345
|
+
*/
|
|
346
|
+
getPendingItems(): Array<() => Promise<TValue>> {
|
|
347
|
+
return this.getAllItems()
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Adds a callback to be called when a task succeeds
|
|
352
|
+
*/
|
|
353
|
+
onSuccess(cb: (result: TValue) => void) {
|
|
354
|
+
this.onSuccessCallbacks.push(cb)
|
|
355
|
+
return () => {
|
|
356
|
+
this.onSuccessCallbacks = this.onSuccessCallbacks.filter((d) => d !== cb)
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Adds a callback to be called when a task errors
|
|
362
|
+
*/
|
|
363
|
+
onError(cb: (error: Error) => void) {
|
|
364
|
+
this.onErrorCallbacks.push(cb)
|
|
365
|
+
return () => {
|
|
366
|
+
this.onErrorCallbacks = this.onErrorCallbacks.filter((d) => d !== cb)
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Adds a callback to be called when a task is settled
|
|
372
|
+
*/
|
|
373
|
+
onSettled(cb: (result: TValue | Error) => void) {
|
|
374
|
+
this.onSettledCallbacks.push(cb)
|
|
375
|
+
return () => {
|
|
376
|
+
this.onSettledCallbacks = this.onSettledCallbacks.filter((d) => d !== cb)
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Starts the queuer and processes items
|
|
382
|
+
*/
|
|
383
|
+
start(): Promise<void> {
|
|
384
|
+
this.running = true
|
|
385
|
+
if (!this.pendingTick && !this.isEmpty()) {
|
|
386
|
+
this.pendingTick = true
|
|
387
|
+
this.tick()
|
|
388
|
+
}
|
|
389
|
+
this.options.onUpdate(this)
|
|
390
|
+
|
|
391
|
+
return new Promise<void>((resolve) => {
|
|
392
|
+
const checkIdle = () => {
|
|
393
|
+
if (this.isIdle()) {
|
|
394
|
+
resolve()
|
|
395
|
+
} else {
|
|
396
|
+
setTimeout(checkIdle, 100)
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
checkIdle()
|
|
400
|
+
})
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Stops the queuer from processing items
|
|
405
|
+
*/
|
|
406
|
+
stop(): void {
|
|
407
|
+
this.running = false
|
|
408
|
+
this.pendingTick = false
|
|
409
|
+
this.options.onUpdate(this)
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Returns true if the queuer is running
|
|
414
|
+
*/
|
|
415
|
+
isRunning(): boolean {
|
|
416
|
+
return this.running
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Returns true if the queuer is running but has no items to process
|
|
421
|
+
*/
|
|
422
|
+
isIdle(): boolean {
|
|
423
|
+
return this.running && this.isEmpty() && this.activeItems.size === 0
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Creates a new AsyncQueuer instance with the given options and returns a bound addItem function.
|
|
429
|
+
* The queuer is automatically started and ready to process items.
|
|
430
|
+
*
|
|
431
|
+
* @example
|
|
432
|
+
* ```ts
|
|
433
|
+
* const enqueue = asyncQueue<string>();
|
|
434
|
+
*
|
|
435
|
+
* // Add items to be processed
|
|
436
|
+
* enqueue(async () => {
|
|
437
|
+
* return 'Hello';
|
|
438
|
+
* });
|
|
439
|
+
* ```
|
|
440
|
+
*
|
|
441
|
+
* @param options - Configuration options for the AsyncQueuer
|
|
442
|
+
* @returns A bound addItem function that can be used to add tasks to the queuer
|
|
443
|
+
*/
|
|
444
|
+
export function asyncQueue<TValue>(options: AsyncQueuerOptions<TValue> = {}) {
|
|
445
|
+
const queuer = new AsyncQueuer<TValue>({ ...options, started: true })
|
|
446
|
+
return queuer.addItem.bind(queuer)
|
|
447
|
+
}
|