@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 @@
|
|
|
1
|
+
{"version":3,"file":"queuer.cjs","sources":["../../src/queuer.ts"],"sourcesContent":["/**\n * Options for configuring a Queuer instance\n */\nexport interface QueuerOptions<TValue> {\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\n /**\n * Default position to get items from during processing\n * @default 'front'\n */\n getItemsFrom?: QueuePosition\n /**\n * Function to determine priority of items in the queuer\n * Higher priority items will be processed first\n */\n getPriority?: (item: TValue) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<TValue>\n /**\n * Maximum number of items allowed in the queuer\n */\n maxSize?: number\n /**\n * Callback fired whenever an item is removed from the queuer\n */\n onGetNextItem?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onUpdate?: (queuer: Queuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately\n */\n started?: boolean\n /**\n * Time in milliseconds to wait between processing items\n */\n wait?: number\n}\n\nconst defaultOptions: Required<QueuerOptions<any>> = {\n addItemsTo: 'back',\n getItemsFrom: 'front',\n getPriority: () => 0,\n initialItems: [],\n maxSize: Infinity,\n onGetNextItem: () => {},\n onUpdate: () => {},\n started: false,\n wait: 0,\n}\n\n/**\n * Position type for addItem and getNextItem operations\n */\nexport type QueuePosition = 'front' | 'back'\n\n/**\n * A flexible queue data structure that defaults to FIFO (First In First Out) behavior\n * with optional position overrides for stack-like or double-ended operations.\n *\n * The queuer can automatically process items as they are added, with configurable\n * wait times between processing each item. Processing can be started/stopped\n * and the queuer will maintain its state.\n *\n * Supports priority-based ordering when a getPriority function is provided.\n * Items with higher priority values will be processed first.\n *\n * Default queue behavior:\n * - addItem(item): adds to back of queuer\n * - getNextItem(): removes and returns from front of queuer\n *\n * Stack (LIFO) behavior:\n * - addItem(item, 'back'): adds to back\n * - getNextItem('back'): removes and returns from back\n *\n * Double-ended queuer behavior:\n * - addItem(item, position): adds to specified position ('front' or 'back')\n * - getNextItem(position): removes and returns from specified position\n *\n * Processing behavior:\n * - start(): begins processing items in the queuer\n * - stop(): pauses processing\n * - wait: configurable delay between processing items\n * - onUpdate/onGetNextItem: callbacks for monitoring queuer state\n *\n * @example\n * ```ts\n * // FIFO queuer\n * const queuer = new Queuer<number>();\n * queuer.addItem(1); // [1]\n * queuer.addItem(2); // [1, 2]\n * queuer.getNextItem(); // returns 1, queuer is [2]\n *\n * // Priority queuer with processing\n * const priorityQueue = new Queuer<number>({\n * getPriority: (n) => n, // Higher numbers have priority\n * started: true, // Begin processing immediately\n * wait: 1000, // Wait 1s between items\n * onGetNextItem: (item) => console.log(item)\n * });\n * priorityQueue.addItem(1); // [1]\n * priorityQueue.addItem(3); // [3, 1] - 3 processed first\n * priorityQueue.addItem(2); // [3, 2, 1]\n * ```\n */\nexport class Queuer<TValue> {\n protected options: Required<QueuerOptions<TValue>>\n private items: Array<TValue> = []\n private executionCount = 0\n private onUpdates: Array<(item: TValue) => void> = []\n private running: boolean\n private pendingTick = false\n\n constructor(initialOptions: QueuerOptions<TValue> = defaultOptions) {\n this.options = { ...defaultOptions, ...initialOptions }\n this.running = this.options.started\n\n for (let i = 0; i < this.options.initialItems.length; i++) {\n const item = this.options.initialItems[i]!\n const isLast = i === this.options.initialItems.length - 1\n this.addItem(item, this.options.addItemsTo, isLast)\n }\n }\n\n /**\n * Processes items in the queuer\n */\n protected tick() {\n if (!this.running) {\n this.pendingTick = false\n return\n }\n while (!this.isEmpty()) {\n const nextItem = this.getNextItem(this.options.getItemsFrom)\n if (nextItem === undefined) {\n break\n }\n this.onUpdates.forEach((cb) => cb(nextItem))\n\n if (this.options.wait > 0) {\n // Use setTimeout to wait before processing next item\n setTimeout(() => this.tick(), this.options.wait)\n return\n }\n\n this.tick()\n }\n this.pendingTick = false\n }\n\n /**\n * Updates the queuer options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<QueuerOptions<TValue>>,\n ): QueuerOptions<TValue> {\n this.options = { ...this.options, ...newOptions }\n return this.options\n }\n\n /**\n * Adds an item to the queuer and starts processing if not already running\n * @returns true if item was added, false if queuer is full\n */\n addItem(\n item: TValue,\n position: QueuePosition = this.options.addItemsTo,\n runOnUpdate: boolean = true,\n ): boolean {\n if (this.isFull()) {\n return false\n }\n\n if (this.options.getPriority !== defaultOptions.getPriority) {\n // If custom priority function is provided, insert based on priority\n const priority = this.options.getPriority(item)\n const insertIndex = this.items.findIndex(\n (existing) => this.options.getPriority(existing) > priority,\n )\n\n if (insertIndex === -1) {\n this.items.push(item)\n } else {\n this.items.splice(insertIndex, 0, item)\n }\n } else {\n // Default FIFO/LIFO behavior\n if (position === 'front') {\n this.items.unshift(item)\n } else {\n this.items.push(item)\n }\n }\n\n if (this.running && !this.pendingTick) {\n this.pendingTick = true\n this.tick()\n }\n if (runOnUpdate) {\n this.options.onUpdate(this)\n }\n return true\n }\n\n /**\n * Removes and returns an item from the queuer using shift (default) or pop\n *\n * @example\n * ```ts\n * // Standard FIFO queuer\n * queuer.getNextItem()\n * // Stack-like behavior (LIFO)\n * queuer.getNextItem('back')\n * ```\n */\n getNextItem(\n position: QueuePosition = this.options.getItemsFrom,\n ): TValue | undefined {\n let item: TValue | undefined\n\n if (position === 'front') {\n item = this.items.shift()\n } else {\n item = this.items.pop()\n }\n\n if (item !== undefined) {\n this.executionCount++\n this.options.onUpdate(this)\n this.options.onGetNextItem(item, this)\n }\n return item\n }\n\n /**\n * Returns an item without removing it\n *\n * @example\n * ```ts\n * // Look at next item to getNextItem\n * queuer.peek()\n * // Look at last item (like stack top)\n * queuer.peek('back')\n * ```\n */\n peek(\n position: QueuePosition = this.options.getItemsFrom,\n ): TValue | undefined {\n if (position === 'front') {\n return this.items[0]\n }\n return this.items[this.items.length - 1]\n }\n\n /**\n * Returns true if the queuer is empty\n */\n isEmpty(): boolean {\n return this.items.length === 0\n }\n\n /**\n * Returns true if the queuer is full\n */\n isFull(): boolean {\n return this.items.length >= this.options.maxSize\n }\n\n /**\n * Returns the current size of the queuer\n */\n size(): number {\n return this.items.length\n }\n\n /**\n * Removes all items from the queuer\n */\n clear(): void {\n this.items = []\n this.options.onUpdate(this)\n }\n\n /**\n * Resets the queuer to its initial state\n */\n reset(withInitialItems?: boolean): void {\n this.clear()\n this.executionCount = 0\n if (withInitialItems) {\n this.items = [...this.options.initialItems]\n }\n this.running = this.options.started\n }\n\n /**\n * Returns a copy of all items in the queuer\n */\n getAllItems(): Array<TValue> {\n return [...this.items]\n }\n\n /**\n * Returns the number of items that have been removed from the queuer\n */\n getExecutionCount(): number {\n return this.executionCount\n }\n\n /**\n * Adds a callback to be called when an item is processed\n */\n onUpdate(cb: (item: TValue) => void) {\n this.onUpdates.push(cb)\n return () => {\n this.onUpdates = this.onUpdates.filter((d) => d !== cb)\n }\n }\n\n /**\n * Stops the queuer from processing items\n */\n stop() {\n this.running = false\n this.pendingTick = false\n this.options.onUpdate(this)\n }\n\n /**\n * Starts the queuer and processes items\n */\n start() {\n this.running = true\n if (!this.pendingTick && !this.isEmpty()) {\n this.pendingTick = true\n this.tick()\n }\n this.options.onUpdate(this)\n }\n\n /**\n * Returns true if the queuer is running\n */\n isRunning() {\n return this.running\n }\n\n /**\n * Returns true if the queuer is running but has no items to process\n */\n isIdle() {\n return this.running && this.isEmpty()\n }\n}\n\n/**\n * Creates a queue that processes items in a queuer immediately upon addition.\n * Items are processed sequentially in FIFO order by default.\n *\n * This is a simplified wrapper around the Queuer class that only exposes the\n * `addItem` method. This queue is always running and will process items as they are added.\n * For more control over queuer processing, use the Queuer class\n * directly which provides methods like `start`, `stop`, `reset`, and more.\n *\n * @example\n * ```ts\n * // Basic sequential processing\n * const processItems = queuer<number>({\n * wait: 1000,\n * onUpdate: (queuer) => console.log(queuer.getAllItems())\n * })\n * processItems(1) // Logs: 1\n * processItems(2) // Logs: 2 after 1 completes\n *\n * // Priority queuer\n * const processPriority = queuer<number>({\n * process: async (n) => console.log(n),\n * getPriority: n => n // Higher numbers processed first\n * })\n * processPriority(1)\n * processPriority(3) // Processed before 1\n * ```\n */\nexport function queue<TValue>(options: QueuerOptions<TValue> = {}) {\n const queuer = new Queuer<TValue>({ ...options, started: true })\n return queuer.addItem.bind(queuer)\n}\n"],"names":[],"mappings":";;AA6CA,MAAM,iBAA+C;AAAA,EACnD,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,aAAa,MAAM;AAAA,EACnB,cAAc,CAAC;AAAA,EACf,SAAS;AAAA,EACT,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,SAAS;AAAA,EACT,MAAM;AACR;AA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AAA;AAAA;AAAA;AAAA;AAAA,EAMd,SAAS;AACA,WAAA,KAAK,WAAW,KAAK,QAAQ;AAAA,EAAA;AAExC;AA8BgB,SAAA,MAAc,UAAiC,IAAI;AAC3D,QAAA,SAAS,IAAI,OAAe,EAAE,GAAG,SAAS,SAAS,MAAM;AACxD,SAAA,OAAO,QAAQ,KAAK,MAAM;AACnC;;;"}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for configuring a Queuer instance
|
|
3
|
+
*/
|
|
4
|
+
export interface QueuerOptions<TValue> {
|
|
5
|
+
/**
|
|
6
|
+
* Default position to add items to the queuer
|
|
7
|
+
* @default 'back'
|
|
8
|
+
*/
|
|
9
|
+
addItemsTo?: QueuePosition;
|
|
10
|
+
/**
|
|
11
|
+
* Default position to get items from during processing
|
|
12
|
+
* @default 'front'
|
|
13
|
+
*/
|
|
14
|
+
getItemsFrom?: QueuePosition;
|
|
15
|
+
/**
|
|
16
|
+
* Function to determine priority of items in the queuer
|
|
17
|
+
* Higher priority items will be processed first
|
|
18
|
+
*/
|
|
19
|
+
getPriority?: (item: TValue) => number;
|
|
20
|
+
/**
|
|
21
|
+
* Initial items to populate the queuer with
|
|
22
|
+
*/
|
|
23
|
+
initialItems?: Array<TValue>;
|
|
24
|
+
/**
|
|
25
|
+
* Maximum number of items allowed in the queuer
|
|
26
|
+
*/
|
|
27
|
+
maxSize?: number;
|
|
28
|
+
/**
|
|
29
|
+
* Callback fired whenever an item is removed from the queuer
|
|
30
|
+
*/
|
|
31
|
+
onGetNextItem?: (item: TValue, queuer: Queuer<TValue>) => void;
|
|
32
|
+
/**
|
|
33
|
+
* Callback fired whenever an item is added or removed from the queuer
|
|
34
|
+
*/
|
|
35
|
+
onUpdate?: (queuer: Queuer<TValue>) => void;
|
|
36
|
+
/**
|
|
37
|
+
* Whether the queuer should start processing tasks immediately
|
|
38
|
+
*/
|
|
39
|
+
started?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Time in milliseconds to wait between processing items
|
|
42
|
+
*/
|
|
43
|
+
wait?: number;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Position type for addItem and getNextItem operations
|
|
47
|
+
*/
|
|
48
|
+
export type QueuePosition = 'front' | 'back';
|
|
49
|
+
/**
|
|
50
|
+
* A flexible queue data structure that defaults to FIFO (First In First Out) behavior
|
|
51
|
+
* with optional position overrides for stack-like or double-ended operations.
|
|
52
|
+
*
|
|
53
|
+
* The queuer can automatically process items as they are added, with configurable
|
|
54
|
+
* wait times between processing each item. Processing can be started/stopped
|
|
55
|
+
* and the queuer will maintain its state.
|
|
56
|
+
*
|
|
57
|
+
* Supports priority-based ordering when a getPriority function is provided.
|
|
58
|
+
* Items with higher priority values will be processed first.
|
|
59
|
+
*
|
|
60
|
+
* Default queue behavior:
|
|
61
|
+
* - addItem(item): adds to back of queuer
|
|
62
|
+
* - getNextItem(): removes and returns from front of queuer
|
|
63
|
+
*
|
|
64
|
+
* Stack (LIFO) behavior:
|
|
65
|
+
* - addItem(item, 'back'): adds to back
|
|
66
|
+
* - getNextItem('back'): removes and returns from back
|
|
67
|
+
*
|
|
68
|
+
* Double-ended queuer behavior:
|
|
69
|
+
* - addItem(item, position): adds to specified position ('front' or 'back')
|
|
70
|
+
* - getNextItem(position): removes and returns from specified position
|
|
71
|
+
*
|
|
72
|
+
* Processing behavior:
|
|
73
|
+
* - start(): begins processing items in the queuer
|
|
74
|
+
* - stop(): pauses processing
|
|
75
|
+
* - wait: configurable delay between processing items
|
|
76
|
+
* - onUpdate/onGetNextItem: callbacks for monitoring queuer state
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* // FIFO queuer
|
|
81
|
+
* const queuer = new Queuer<number>();
|
|
82
|
+
* queuer.addItem(1); // [1]
|
|
83
|
+
* queuer.addItem(2); // [1, 2]
|
|
84
|
+
* queuer.getNextItem(); // returns 1, queuer is [2]
|
|
85
|
+
*
|
|
86
|
+
* // Priority queuer with processing
|
|
87
|
+
* const priorityQueue = new Queuer<number>({
|
|
88
|
+
* getPriority: (n) => n, // Higher numbers have priority
|
|
89
|
+
* started: true, // Begin processing immediately
|
|
90
|
+
* wait: 1000, // Wait 1s between items
|
|
91
|
+
* onGetNextItem: (item) => console.log(item)
|
|
92
|
+
* });
|
|
93
|
+
* priorityQueue.addItem(1); // [1]
|
|
94
|
+
* priorityQueue.addItem(3); // [3, 1] - 3 processed first
|
|
95
|
+
* priorityQueue.addItem(2); // [3, 2, 1]
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
export declare class Queuer<TValue> {
|
|
99
|
+
protected options: Required<QueuerOptions<TValue>>;
|
|
100
|
+
private items;
|
|
101
|
+
private executionCount;
|
|
102
|
+
private onUpdates;
|
|
103
|
+
private running;
|
|
104
|
+
private pendingTick;
|
|
105
|
+
constructor(initialOptions?: QueuerOptions<TValue>);
|
|
106
|
+
/**
|
|
107
|
+
* Processes items in the queuer
|
|
108
|
+
*/
|
|
109
|
+
protected tick(): void;
|
|
110
|
+
/**
|
|
111
|
+
* Updates the queuer options
|
|
112
|
+
* Returns the new options state
|
|
113
|
+
*/
|
|
114
|
+
setOptions(newOptions: Partial<QueuerOptions<TValue>>): QueuerOptions<TValue>;
|
|
115
|
+
/**
|
|
116
|
+
* Adds an item to the queuer and starts processing if not already running
|
|
117
|
+
* @returns true if item was added, false if queuer is full
|
|
118
|
+
*/
|
|
119
|
+
addItem(item: TValue, position?: QueuePosition, runOnUpdate?: boolean): boolean;
|
|
120
|
+
/**
|
|
121
|
+
* Removes and returns an item from the queuer using shift (default) or pop
|
|
122
|
+
*
|
|
123
|
+
* @example
|
|
124
|
+
* ```ts
|
|
125
|
+
* // Standard FIFO queuer
|
|
126
|
+
* queuer.getNextItem()
|
|
127
|
+
* // Stack-like behavior (LIFO)
|
|
128
|
+
* queuer.getNextItem('back')
|
|
129
|
+
* ```
|
|
130
|
+
*/
|
|
131
|
+
getNextItem(position?: QueuePosition): TValue | undefined;
|
|
132
|
+
/**
|
|
133
|
+
* Returns an item without removing it
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts
|
|
137
|
+
* // Look at next item to getNextItem
|
|
138
|
+
* queuer.peek()
|
|
139
|
+
* // Look at last item (like stack top)
|
|
140
|
+
* queuer.peek('back')
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
peek(position?: QueuePosition): TValue | undefined;
|
|
144
|
+
/**
|
|
145
|
+
* Returns true if the queuer is empty
|
|
146
|
+
*/
|
|
147
|
+
isEmpty(): boolean;
|
|
148
|
+
/**
|
|
149
|
+
* Returns true if the queuer is full
|
|
150
|
+
*/
|
|
151
|
+
isFull(): boolean;
|
|
152
|
+
/**
|
|
153
|
+
* Returns the current size of the queuer
|
|
154
|
+
*/
|
|
155
|
+
size(): number;
|
|
156
|
+
/**
|
|
157
|
+
* Removes all items from the queuer
|
|
158
|
+
*/
|
|
159
|
+
clear(): void;
|
|
160
|
+
/**
|
|
161
|
+
* Resets the queuer to its initial state
|
|
162
|
+
*/
|
|
163
|
+
reset(withInitialItems?: boolean): void;
|
|
164
|
+
/**
|
|
165
|
+
* Returns a copy of all items in the queuer
|
|
166
|
+
*/
|
|
167
|
+
getAllItems(): Array<TValue>;
|
|
168
|
+
/**
|
|
169
|
+
* Returns the number of items that have been removed from the queuer
|
|
170
|
+
*/
|
|
171
|
+
getExecutionCount(): number;
|
|
172
|
+
/**
|
|
173
|
+
* Adds a callback to be called when an item is processed
|
|
174
|
+
*/
|
|
175
|
+
onUpdate(cb: (item: TValue) => void): () => void;
|
|
176
|
+
/**
|
|
177
|
+
* Stops the queuer from processing items
|
|
178
|
+
*/
|
|
179
|
+
stop(): void;
|
|
180
|
+
/**
|
|
181
|
+
* Starts the queuer and processes items
|
|
182
|
+
*/
|
|
183
|
+
start(): void;
|
|
184
|
+
/**
|
|
185
|
+
* Returns true if the queuer is running
|
|
186
|
+
*/
|
|
187
|
+
isRunning(): boolean;
|
|
188
|
+
/**
|
|
189
|
+
* Returns true if the queuer is running but has no items to process
|
|
190
|
+
*/
|
|
191
|
+
isIdle(): boolean;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Creates a queue that processes items in a queuer immediately upon addition.
|
|
195
|
+
* Items are processed sequentially in FIFO order by default.
|
|
196
|
+
*
|
|
197
|
+
* This is a simplified wrapper around the Queuer class that only exposes the
|
|
198
|
+
* `addItem` method. This queue is always running and will process items as they are added.
|
|
199
|
+
* For more control over queuer processing, use the Queuer class
|
|
200
|
+
* directly which provides methods like `start`, `stop`, `reset`, and more.
|
|
201
|
+
*
|
|
202
|
+
* @example
|
|
203
|
+
* ```ts
|
|
204
|
+
* // Basic sequential processing
|
|
205
|
+
* const processItems = queuer<number>({
|
|
206
|
+
* wait: 1000,
|
|
207
|
+
* onUpdate: (queuer) => console.log(queuer.getAllItems())
|
|
208
|
+
* })
|
|
209
|
+
* processItems(1) // Logs: 1
|
|
210
|
+
* processItems(2) // Logs: 2 after 1 completes
|
|
211
|
+
*
|
|
212
|
+
* // Priority queuer
|
|
213
|
+
* const processPriority = queuer<number>({
|
|
214
|
+
* process: async (n) => console.log(n),
|
|
215
|
+
* getPriority: n => n // Higher numbers processed first
|
|
216
|
+
* })
|
|
217
|
+
* processPriority(1)
|
|
218
|
+
* processPriority(3) // Processed before 1
|
|
219
|
+
* ```
|
|
220
|
+
*/
|
|
221
|
+
export declare function queue<TValue>(options?: QueuerOptions<TValue>): (item: TValue, position?: QueuePosition, runOnUpdate?: boolean) => boolean;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const defaultOptions = {
|
|
4
|
+
enabled: true,
|
|
5
|
+
limit: 1,
|
|
6
|
+
window: 0
|
|
7
|
+
};
|
|
8
|
+
class RateLimiter {
|
|
9
|
+
constructor(fn, initialOptions) {
|
|
10
|
+
this.fn = fn;
|
|
11
|
+
this.executionCount = 0;
|
|
12
|
+
this.rejectionCount = 0;
|
|
13
|
+
this.executionTimes = [];
|
|
14
|
+
this.options = {
|
|
15
|
+
...defaultOptions,
|
|
16
|
+
...initialOptions
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Updates the rate limiter options
|
|
21
|
+
* Returns the new options state
|
|
22
|
+
*/
|
|
23
|
+
setOptions(newOptions) {
|
|
24
|
+
this.options = {
|
|
25
|
+
...this.options,
|
|
26
|
+
...newOptions
|
|
27
|
+
};
|
|
28
|
+
return this.options;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Returns the number of times the function has been executed
|
|
32
|
+
*/
|
|
33
|
+
getExecutionCount() {
|
|
34
|
+
return this.executionCount;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Returns the number of times the function has been rejected
|
|
38
|
+
*/
|
|
39
|
+
getRejectionCount() {
|
|
40
|
+
return this.rejectionCount;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Returns the number of remaining executions allowed in the current window
|
|
44
|
+
*/
|
|
45
|
+
getRemainingInWindow() {
|
|
46
|
+
this.cleanupOldExecutions();
|
|
47
|
+
return Math.max(0, this.options.limit - this.executionTimes.length);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Attempts to execute the rate-limited function if within the configured limits.
|
|
51
|
+
* Will reject execution if the number of calls in the current window exceeds the limit.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```ts
|
|
55
|
+
* const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
|
|
56
|
+
*
|
|
57
|
+
* // First 5 calls will return true
|
|
58
|
+
* rateLimiter.maybeExecute('arg1', 'arg2'); // true
|
|
59
|
+
*
|
|
60
|
+
* // Additional calls within the window will return false
|
|
61
|
+
* rateLimiter.maybeExecute('arg1', 'arg2'); // false
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
maybeExecute(...args) {
|
|
65
|
+
this.cleanupOldExecutions();
|
|
66
|
+
if (this.executionTimes.length < this.options.limit) {
|
|
67
|
+
this.executeFunction(...args);
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
this.rejectFunction();
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
executeFunction(...args) {
|
|
74
|
+
if (!this.options.enabled) return;
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
this.executionCount++;
|
|
77
|
+
this.executionTimes.push(now);
|
|
78
|
+
this.fn(...args);
|
|
79
|
+
}
|
|
80
|
+
rejectFunction() {
|
|
81
|
+
this.rejectionCount++;
|
|
82
|
+
if (this.options.onReject) {
|
|
83
|
+
const oldestExecution = Math.min(...this.executionTimes);
|
|
84
|
+
const msUntilNextWindow = oldestExecution + this.options.window - Date.now();
|
|
85
|
+
this.options.onReject({
|
|
86
|
+
msUntilNextWindow,
|
|
87
|
+
currentExecutions: this.executionTimes.length,
|
|
88
|
+
limit: this.options.limit,
|
|
89
|
+
rejectionCount: this.rejectionCount
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
cleanupOldExecutions() {
|
|
94
|
+
const now = Date.now();
|
|
95
|
+
const windowStart = now - this.options.window;
|
|
96
|
+
this.executionTimes = this.executionTimes.filter(
|
|
97
|
+
(time) => time > windowStart
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Resets the rate limiter state
|
|
102
|
+
*/
|
|
103
|
+
reset() {
|
|
104
|
+
this.executionTimes = [];
|
|
105
|
+
this.executionCount = 0;
|
|
106
|
+
this.rejectionCount = 0;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function rateLimit(fn, initialOptions) {
|
|
110
|
+
const rateLimiter = new RateLimiter(fn, initialOptions);
|
|
111
|
+
return rateLimiter.maybeExecute.bind(rateLimiter);
|
|
112
|
+
}
|
|
113
|
+
exports.RateLimiter = RateLimiter;
|
|
114
|
+
exports.rateLimit = rateLimit;
|
|
115
|
+
//# sourceMappingURL=rate-limiter.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limiter.cjs","sources":["../../src/rate-limiter.ts"],"sourcesContent":["/**\n * Information about a rate limit rejection\n */\nexport interface RateLimitRejectionInfo {\n /**\n * Number of milliseconds until the next execution will be possible\n */\n msUntilNextWindow: number\n /**\n * Current number of executions in the window\n */\n currentExecutions: number\n /**\n * Maximum allowed executions per window\n */\n limit: number\n /**\n * Total number of rejections that have occurred\n */\n rejectionCount: number\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (info: RateLimitRejectionInfo) => void\n}\n\nconst defaultOptions: Required<Omit<RateLimiterOptions, 'onReject'>> = {\n enabled: true,\n limit: 1,\n window: 0,\n}\n\n/**\n * A class that creates a rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<\n TFn extends (...args: Array<any>) => any,\n TArgs extends Parameters<TFn>,\n> {\n private executionCount = 0\n private rejectionCount = 0\n private executionTimes: Array<number> = []\n private options: RateLimiterOptions\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<RateLimiterOptions>): RateLimiterOptions {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this.executionCount\n }\n\n /**\n * Returns the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this.rejectionCount\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this.options.limit - this.executionTimes.length)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute(...args: TArgs): boolean {\n this.cleanupOldExecutions()\n\n if (this.executionTimes.length < this.options.limit) {\n this.executeFunction(...args)\n return true\n }\n\n this.rejectFunction()\n\n return false\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this.options.enabled) return\n const now = Date.now()\n this.executionCount++\n this.executionTimes.push(now)\n this.fn(...args)\n }\n\n private rejectFunction(): void {\n this.rejectionCount++\n if (this.options.onReject) {\n const oldestExecution = Math.min(...this.executionTimes)\n const msUntilNextWindow =\n oldestExecution + this.options.window - Date.now()\n\n this.options.onReject({\n msUntilNextWindow,\n currentExecutions: this.executionTimes.length,\n limit: this.options.limit,\n rejectionCount: this.rejectionCount,\n })\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this.options.window\n this.executionTimes = this.executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this.executionTimes = []\n this.executionCount = 0\n this.rejectionCount = 0\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * onReject: ({ msUntilNextWindow }) => {\n * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function rateLimit<TFn extends (...args: Array<any>) => any>(\n fn: TFn,\n initialOptions: Omit<RateLimiterOptions, 'enabled'>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":";;AA6CA,MAAM,iBAAiE;AAAA,EACrE,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AACV;AA2BO,MAAM,YAGX;AAAA,EAMA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,iBAAiB;AACzB,SAAQ,iBAAiB;AACzB,SAAQ,iBAAgC,CAAC;AAOvC,SAAK,UAAU;AAAA,MACb,GAAG;AAA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AAAA,MAAA,CACtB;AAAA,IAAA;AAAA,EACH;AAAA,EAGM,uBAA6B;AAC7B,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,cAAc,MAAM,KAAK,QAAQ;AAClC,SAAA,iBAAiB,KAAK,eAAe;AAAA,MACxC,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,QAAc;AACZ,SAAK,iBAAiB,CAAC;AACvB,SAAK,iBAAiB;AACtB,SAAK,iBAAiB;AAAA,EAAA;AAE1B;AAgCgB,SAAA,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AAC/C,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Information about a rate limit rejection
|
|
3
|
+
*/
|
|
4
|
+
export interface RateLimitRejectionInfo {
|
|
5
|
+
/**
|
|
6
|
+
* Number of milliseconds until the next execution will be possible
|
|
7
|
+
*/
|
|
8
|
+
msUntilNextWindow: number;
|
|
9
|
+
/**
|
|
10
|
+
* Current number of executions in the window
|
|
11
|
+
*/
|
|
12
|
+
currentExecutions: number;
|
|
13
|
+
/**
|
|
14
|
+
* Maximum allowed executions per window
|
|
15
|
+
*/
|
|
16
|
+
limit: number;
|
|
17
|
+
/**
|
|
18
|
+
* Total number of rejections that have occurred
|
|
19
|
+
*/
|
|
20
|
+
rejectionCount: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Options for configuring a rate-limited function
|
|
24
|
+
*/
|
|
25
|
+
export interface RateLimiterOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
28
|
+
* Defaults to true.
|
|
29
|
+
*/
|
|
30
|
+
enabled?: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Maximum number of executions allowed within the time window
|
|
33
|
+
*/
|
|
34
|
+
limit: number;
|
|
35
|
+
/**
|
|
36
|
+
* Time window in milliseconds within which the limit applies
|
|
37
|
+
*/
|
|
38
|
+
window: number;
|
|
39
|
+
/**
|
|
40
|
+
* Optional callback function that is called when an execution is rejected due to rate limiting
|
|
41
|
+
*/
|
|
42
|
+
onReject?: (info: RateLimitRejectionInfo) => void;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* A class that creates a rate-limited function.
|
|
46
|
+
*
|
|
47
|
+
* Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
|
|
48
|
+
* then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
|
|
49
|
+
* all executions happen immediately, followed by a complete block.
|
|
50
|
+
*
|
|
51
|
+
* For smoother execution patterns, consider using:
|
|
52
|
+
* - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
|
|
53
|
+
* - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
|
|
54
|
+
*
|
|
55
|
+
* Rate limiting is best used for hard API limits or resource constraints. For UI updates or
|
|
56
|
+
* smoothing out frequent events, throttling or debouncing usually provide better user experience.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```ts
|
|
60
|
+
* const rateLimiter = new RateLimiter(
|
|
61
|
+
* (id: string) => api.getData(id),
|
|
62
|
+
* { limit: 5, window: 1000 } // 5 calls per second
|
|
63
|
+
* );
|
|
64
|
+
*
|
|
65
|
+
* // Will execute immediately until limit reached, then block
|
|
66
|
+
* rateLimiter.maybeExecute('123');
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export declare class RateLimiter<TFn extends (...args: Array<any>) => any, TArgs extends Parameters<TFn>> {
|
|
70
|
+
private fn;
|
|
71
|
+
private executionCount;
|
|
72
|
+
private rejectionCount;
|
|
73
|
+
private executionTimes;
|
|
74
|
+
private options;
|
|
75
|
+
constructor(fn: TFn, initialOptions: RateLimiterOptions);
|
|
76
|
+
/**
|
|
77
|
+
* Updates the rate limiter options
|
|
78
|
+
* Returns the new options state
|
|
79
|
+
*/
|
|
80
|
+
setOptions(newOptions: Partial<RateLimiterOptions>): RateLimiterOptions;
|
|
81
|
+
/**
|
|
82
|
+
* Returns the number of times the function has been executed
|
|
83
|
+
*/
|
|
84
|
+
getExecutionCount(): number;
|
|
85
|
+
/**
|
|
86
|
+
* Returns the number of times the function has been rejected
|
|
87
|
+
*/
|
|
88
|
+
getRejectionCount(): number;
|
|
89
|
+
/**
|
|
90
|
+
* Returns the number of remaining executions allowed in the current window
|
|
91
|
+
*/
|
|
92
|
+
getRemainingInWindow(): number;
|
|
93
|
+
/**
|
|
94
|
+
* Attempts to execute the rate-limited function if within the configured limits.
|
|
95
|
+
* Will reject execution if the number of calls in the current window exceeds the limit.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
|
|
100
|
+
*
|
|
101
|
+
* // First 5 calls will return true
|
|
102
|
+
* rateLimiter.maybeExecute('arg1', 'arg2'); // true
|
|
103
|
+
*
|
|
104
|
+
* // Additional calls within the window will return false
|
|
105
|
+
* rateLimiter.maybeExecute('arg1', 'arg2'); // false
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
maybeExecute(...args: TArgs): boolean;
|
|
109
|
+
private executeFunction;
|
|
110
|
+
private rejectFunction;
|
|
111
|
+
private cleanupOldExecutions;
|
|
112
|
+
/**
|
|
113
|
+
* Resets the rate limiter state
|
|
114
|
+
*/
|
|
115
|
+
reset(): void;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
|
|
119
|
+
*
|
|
120
|
+
* Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
|
|
121
|
+
* - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
|
|
122
|
+
* - A throttler ensures even spacing between executions, which can be better for consistent performance
|
|
123
|
+
* - A debouncer collapses multiple calls into one, which is better for handling bursts of events
|
|
124
|
+
*
|
|
125
|
+
* Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
|
|
126
|
+
* need to enforce a hard limit on the number of executions within a time period.
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```ts
|
|
130
|
+
* // Rate limit to 5 calls per minute
|
|
131
|
+
* const rateLimited = rateLimit(makeApiCall, {
|
|
132
|
+
* limit: 5,
|
|
133
|
+
* window: 60000,
|
|
134
|
+
* onReject: ({ msUntilNextWindow }) => {
|
|
135
|
+
* console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);
|
|
136
|
+
* }
|
|
137
|
+
* });
|
|
138
|
+
*
|
|
139
|
+
* // First 5 calls will execute immediately
|
|
140
|
+
* // Additional calls will be rejected until the minute window resets
|
|
141
|
+
* rateLimited();
|
|
142
|
+
*
|
|
143
|
+
* // For more even execution, consider using throttle instead:
|
|
144
|
+
* const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
export declare function rateLimit<TFn extends (...args: Array<any>) => any>(fn: TFn, initialOptions: Omit<RateLimiterOptions, 'enabled'>): (...args: Parameters<TFn>) => boolean;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const defaultOptions = {
|
|
4
|
+
enabled: true,
|
|
5
|
+
leading: true,
|
|
6
|
+
trailing: true,
|
|
7
|
+
wait: 0
|
|
8
|
+
};
|
|
9
|
+
class Throttler {
|
|
10
|
+
constructor(fn, initialOptions) {
|
|
11
|
+
this.fn = fn;
|
|
12
|
+
this.executionCount = 0;
|
|
13
|
+
this.lastExecutionTime = 0;
|
|
14
|
+
this.options = {
|
|
15
|
+
...defaultOptions,
|
|
16
|
+
...initialOptions
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Updates the throttler options
|
|
21
|
+
* Returns the new options state
|
|
22
|
+
*/
|
|
23
|
+
setOptions(newOptions) {
|
|
24
|
+
this.options = {
|
|
25
|
+
...this.options,
|
|
26
|
+
...newOptions
|
|
27
|
+
};
|
|
28
|
+
return this.options;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Returns the number of times the function has been executed
|
|
32
|
+
*/
|
|
33
|
+
getExecutionCount() {
|
|
34
|
+
return this.executionCount;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Returns the last execution time
|
|
38
|
+
*/
|
|
39
|
+
getLastExecutionTime() {
|
|
40
|
+
return this.lastExecutionTime;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Returns the next execution time
|
|
44
|
+
*/
|
|
45
|
+
getNextExecutionTime() {
|
|
46
|
+
return this.lastExecutionTime + this.options.wait;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Attempts to execute the throttled function. The execution behavior depends on the throttler options:
|
|
50
|
+
*
|
|
51
|
+
* - If enough time has passed since the last execution (>= wait period):
|
|
52
|
+
* - With leading=true: Executes immediately
|
|
53
|
+
* - With leading=false: Waits for the next trailing execution
|
|
54
|
+
*
|
|
55
|
+
* - If within the wait period:
|
|
56
|
+
* - With trailing=true: Schedules execution for end of wait period
|
|
57
|
+
* - With trailing=false: Drops the execution
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```ts
|
|
61
|
+
* const throttled = new Throttler(fn, { wait: 1000 });
|
|
62
|
+
*
|
|
63
|
+
* // First call executes immediately
|
|
64
|
+
* throttled.maybeExecute('a', 'b');
|
|
65
|
+
*
|
|
66
|
+
* // Call during wait period - gets throttled
|
|
67
|
+
* throttled.maybeExecute('c', 'd');
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
maybeExecute(...args) {
|
|
71
|
+
const now = Date.now();
|
|
72
|
+
const timeSinceLastExecution = now - this.lastExecutionTime;
|
|
73
|
+
if (timeSinceLastExecution >= this.options.wait) {
|
|
74
|
+
if (this.options.leading) {
|
|
75
|
+
this.executeFunction(...args);
|
|
76
|
+
}
|
|
77
|
+
this.lastExecutionTime = now;
|
|
78
|
+
} else {
|
|
79
|
+
this.lastArgs = args;
|
|
80
|
+
if (!this.timeoutId && this.options.trailing) {
|
|
81
|
+
this.timeoutId = setTimeout(() => {
|
|
82
|
+
if (this.lastArgs) {
|
|
83
|
+
this.executeFunction(...this.lastArgs);
|
|
84
|
+
this.lastArgs = void 0;
|
|
85
|
+
}
|
|
86
|
+
this.lastExecutionTime = Date.now();
|
|
87
|
+
this.timeoutId = void 0;
|
|
88
|
+
}, this.options.wait - timeSinceLastExecution);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
executeFunction(...args) {
|
|
93
|
+
if (!this.options.enabled) return;
|
|
94
|
+
this.executionCount++;
|
|
95
|
+
this.fn(...args);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Cancels any pending trailing execution and clears internal state.
|
|
99
|
+
*
|
|
100
|
+
* If a trailing execution is scheduled (due to throttling with trailing=true),
|
|
101
|
+
* this will prevent that execution from occurring. The internal timeout and
|
|
102
|
+
* stored arguments will be cleared.
|
|
103
|
+
*
|
|
104
|
+
* Has no effect if there is no pending execution.
|
|
105
|
+
*/
|
|
106
|
+
cancel() {
|
|
107
|
+
if (this.timeoutId) {
|
|
108
|
+
clearTimeout(this.timeoutId);
|
|
109
|
+
this.timeoutId = void 0;
|
|
110
|
+
this.lastArgs = void 0;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function throttle(fn, initialOptions) {
|
|
115
|
+
const throttler = new Throttler(fn, initialOptions);
|
|
116
|
+
return throttler.maybeExecute.bind(throttler);
|
|
117
|
+
}
|
|
118
|
+
exports.Throttler = Throttler;
|
|
119
|
+
exports.throttle = throttle;
|
|
120
|
+
//# sourceMappingURL=throttler.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"throttler.cjs","sources":["../../src/throttler.ts"],"sourcesContent":["/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once\n */\n wait: number\n}\n\nconst defaultOptions: Required<ThrottlerOptions> = {\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For rate limiting or hard API limits, consider using RateLimiter instead.\n * For collapsing rapid-fire events, consider using Debouncer.\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<\n TFn extends (...args: Array<any>) => any,\n TArgs extends Parameters<TFn>,\n> {\n private executionCount = 0\n private lastArgs: TArgs | undefined\n private lastExecutionTime = 0\n private options: Required<ThrottlerOptions>\n private timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: ThrottlerOptions,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the throttler options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<ThrottlerOptions>,\n ): Required<ThrottlerOptions> {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this.executionCount\n }\n\n /**\n * Returns the last execution time\n */\n getLastExecutionTime(): number {\n return this.lastExecutionTime\n }\n\n /**\n * Returns the next execution time\n */\n getNextExecutionTime(): number {\n return this.lastExecutionTime + this.options.wait\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute(...args: TArgs): void {\n const now = Date.now()\n const timeSinceLastExecution = now - this.lastExecutionTime\n\n // Handle leading execution\n if (timeSinceLastExecution >= this.options.wait) {\n if (this.options.leading) {\n this.executeFunction(...args)\n }\n this.lastExecutionTime = now\n } else {\n // Store the most recent arguments for potential trailing execution\n this.lastArgs = args\n\n // Set up trailing execution if not already scheduled\n if (!this.timeoutId && this.options.trailing) {\n this.timeoutId = setTimeout(() => {\n if (this.lastArgs) {\n this.executeFunction(...this.lastArgs)\n this.lastArgs = undefined\n }\n this.lastExecutionTime = Date.now()\n this.timeoutId = undefined\n }, this.options.wait - timeSinceLastExecution)\n }\n }\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this.options.enabled) return\n this.executionCount++\n this.fn(...args)\n }\n\n /**\n * Cancels any pending trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel(): void {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = undefined\n this.lastArgs = undefined\n }\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * @example\n * ```ts\n * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends (...args: Array<any>) => any>(\n fn: TFn,\n initialOptions: Omit<ThrottlerOptions, 'enabled'>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute.bind(throttler)\n}\n"],"names":[],"mappings":";;AAyBA,MAAM,iBAA6C;AAAA,EACjD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AA8BO,MAAM,UAGX;AAAA,EAOA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAQ,iBAAiB;AAEzB,SAAQ,oBAAoB;AAQ1B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YAC4B;AAC5B,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AACtB,WAA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