@tanstack/pacer-lite 0.1.0 → 0.1.1

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.
Files changed (62) hide show
  1. package/dist/index.cjs +16 -0
  2. package/dist/index.d.cts +6 -0
  3. package/dist/index.d.ts +6 -0
  4. package/dist/{esm/index.js → index.js} +2 -13
  5. package/dist/lite-batcher.cjs +175 -0
  6. package/dist/lite-batcher.cjs.map +1 -0
  7. package/dist/{cjs/lite-batcher.d.cts → lite-batcher.d.cts} +89 -85
  8. package/dist/{esm/lite-batcher.d.ts → lite-batcher.d.ts} +89 -85
  9. package/dist/lite-batcher.js +173 -0
  10. package/dist/lite-batcher.js.map +1 -0
  11. package/dist/lite-debouncer.cjs +125 -0
  12. package/dist/lite-debouncer.cjs.map +1 -0
  13. package/dist/{cjs/lite-debouncer.d.cts → lite-debouncer.d.cts} +53 -47
  14. package/dist/{esm/lite-debouncer.d.ts → lite-debouncer.d.ts} +53 -47
  15. package/dist/lite-debouncer.js +123 -0
  16. package/dist/lite-debouncer.js.map +1 -0
  17. package/dist/lite-queuer.cjs +208 -0
  18. package/dist/lite-queuer.cjs.map +1 -0
  19. package/dist/lite-queuer.d.cts +243 -0
  20. package/dist/lite-queuer.d.ts +243 -0
  21. package/dist/lite-queuer.js +206 -0
  22. package/dist/lite-queuer.js.map +1 -0
  23. package/dist/lite-rate-limiter.cjs +149 -0
  24. package/dist/lite-rate-limiter.cjs.map +1 -0
  25. package/dist/{cjs/lite-rate-limiter.d.cts → lite-rate-limiter.d.cts} +73 -67
  26. package/dist/{esm/lite-rate-limiter.d.ts → lite-rate-limiter.d.ts} +73 -67
  27. package/dist/lite-rate-limiter.js +147 -0
  28. package/dist/lite-rate-limiter.js.map +1 -0
  29. package/dist/lite-throttler.cjs +127 -0
  30. package/dist/lite-throttler.cjs.map +1 -0
  31. package/dist/{cjs/lite-throttler.d.cts → lite-throttler.d.cts} +60 -54
  32. package/dist/{esm/lite-throttler.d.ts → lite-throttler.d.ts} +60 -54
  33. package/dist/lite-throttler.js +125 -0
  34. package/dist/lite-throttler.js.map +1 -0
  35. package/package.json +22 -59
  36. package/dist/cjs/index.cjs +0 -18
  37. package/dist/cjs/index.cjs.map +0 -1
  38. package/dist/cjs/index.d.cts +0 -5
  39. package/dist/cjs/lite-batcher.cjs +0 -92
  40. package/dist/cjs/lite-batcher.cjs.map +0 -1
  41. package/dist/cjs/lite-debouncer.cjs +0 -59
  42. package/dist/cjs/lite-debouncer.cjs.map +0 -1
  43. package/dist/cjs/lite-queuer.cjs +0 -171
  44. package/dist/cjs/lite-queuer.cjs.map +0 -1
  45. package/dist/cjs/lite-queuer.d.cts +0 -239
  46. package/dist/cjs/lite-rate-limiter.cjs +0 -95
  47. package/dist/cjs/lite-rate-limiter.cjs.map +0 -1
  48. package/dist/cjs/lite-throttler.cjs +0 -63
  49. package/dist/cjs/lite-throttler.cjs.map +0 -1
  50. package/dist/esm/index.d.ts +0 -5
  51. package/dist/esm/index.js.map +0 -1
  52. package/dist/esm/lite-batcher.js +0 -92
  53. package/dist/esm/lite-batcher.js.map +0 -1
  54. package/dist/esm/lite-debouncer.js +0 -59
  55. package/dist/esm/lite-debouncer.js.map +0 -1
  56. package/dist/esm/lite-queuer.d.ts +0 -239
  57. package/dist/esm/lite-queuer.js +0 -171
  58. package/dist/esm/lite-queuer.js.map +0 -1
  59. package/dist/esm/lite-rate-limiter.js +0 -95
  60. package/dist/esm/lite-rate-limiter.js.map +0 -1
  61. package/dist/esm/lite-throttler.js +0 -63
  62. package/dist/esm/lite-throttler.js.map +0 -1
@@ -0,0 +1,173 @@
1
+ //#region src/lite-batcher.ts
2
+ /**
3
+ * A lightweight class that collects items and processes them in batches.
4
+ *
5
+ * This is an alternative to the Batcher in the core @tanstack/pacer package, but is more
6
+ * suitable for libraries and npm packages that need minimal overhead. Unlike the core Batcher,
7
+ * this version does not use TanStack Store for state management, has no devtools integration,
8
+ * no callbacks, and provides only essential batching functionality.
9
+ *
10
+ * Batching is a technique for grouping multiple operations together to be processed as a single unit.
11
+ * This synchronous version is lighter weight and often all you need.
12
+ *
13
+ * The Batcher provides a flexible way to implement batching with configurable:
14
+ * - Maximum batch size (number of items per batch)
15
+ * - Time-based batching (process after X milliseconds)
16
+ * - Custom batch processing logic via getShouldExecute
17
+ *
18
+ * Features included:
19
+ * - Core batching functionality (addItem, flush, clear, cancel)
20
+ * - Size-based batching (maxSize)
21
+ * - Time-based batching (wait timeout)
22
+ * - Custom condition batching (getShouldExecute)
23
+ * - Manual processing controls
24
+ * - Public mutable options
25
+ * - Callback support for monitoring batch execution and state changes
26
+ *
27
+ * Features NOT included (compared to core Batcher):
28
+ * - No TanStack Store state management
29
+ * - No devtools integration
30
+ * - No complex state tracking (execution counts, etc.)
31
+ * - No reactive state management
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * // Basic batching
36
+ * const batcher = new LiteBatcher<number>(
37
+ * (items) => console.log('Processing batch:', items),
38
+ * {
39
+ * maxSize: 5,
40
+ * wait: 2000,
41
+ * onExecute: (batch, batcher) => {
42
+ * console.log('Batch executed with', batch.length, 'items');
43
+ * },
44
+ * onItemsChange: (batcher) => {
45
+ * console.log('Batch size changed to:', batcher.size);
46
+ * }
47
+ * }
48
+ * );
49
+ *
50
+ * batcher.addItem(1);
51
+ * batcher.addItem(2);
52
+ * // After 2 seconds or when 5 items are added, whichever comes first,
53
+ * // the batch will be processed
54
+ * ```
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * // Custom condition batching
59
+ * const batcher = new LiteBatcher<Task>(
60
+ * (items) => processTasks(items),
61
+ * {
62
+ * getShouldExecute: (items) => items.some(task => task.urgent),
63
+ * maxSize: 10,
64
+ * }
65
+ * );
66
+ *
67
+ * batcher.addItem({ name: 'normal', urgent: false });
68
+ * batcher.addItem({ name: 'urgent', urgent: true }); // Triggers immediate processing
69
+ * ```
70
+ */
71
+ var LiteBatcher = class {
72
+ constructor(fn, options = {}) {
73
+ this.fn = fn;
74
+ this.options = options;
75
+ this.items = [];
76
+ this.timeoutId = null;
77
+ this._isPending = false;
78
+ this.addItem = (item) => {
79
+ this.items.push(item);
80
+ this._isPending = this.options.wait !== Infinity;
81
+ this.options.onItemsChange?.(this);
82
+ if (this.items.length >= this.options.maxSize || this.options.getShouldExecute(this.items, this)) this.execute();
83
+ else if (this.options.wait !== Infinity) {
84
+ this.clearTimeout();
85
+ this.timeoutId = setTimeout(() => this.execute(), this.getWait());
86
+ }
87
+ };
88
+ this.execute = () => {
89
+ if (this.items.length === 0) return;
90
+ const batch = this.peekAllItems();
91
+ this.clear();
92
+ this.fn(batch);
93
+ this.options.onExecute?.(batch, this);
94
+ };
95
+ this.flush = () => {
96
+ this.clearTimeout();
97
+ this.execute();
98
+ };
99
+ this.peekAllItems = () => {
100
+ return [...this.items];
101
+ };
102
+ this.clearTimeout = () => {
103
+ if (this.timeoutId) {
104
+ clearTimeout(this.timeoutId);
105
+ this.timeoutId = null;
106
+ }
107
+ };
108
+ this.clear = () => {
109
+ const hadItems = this.items.length > 0;
110
+ this.items = [];
111
+ this._isPending = false;
112
+ if (hadItems) this.options.onItemsChange?.(this);
113
+ };
114
+ this.cancel = () => {
115
+ this.clearTimeout();
116
+ this._isPending = false;
117
+ };
118
+ this.options.maxSize = this.options.maxSize ?? Infinity;
119
+ this.options.started = this.options.started ?? true;
120
+ this.options.wait = this.options.wait ?? Infinity;
121
+ this.options.getShouldExecute = this.options.getShouldExecute ?? (() => false);
122
+ }
123
+ /**
124
+ * Number of items currently in the batch
125
+ */
126
+ get size() {
127
+ return this.items.length;
128
+ }
129
+ /**
130
+ * Whether the batch has no items to process (items array is empty)
131
+ */
132
+ get isEmpty() {
133
+ return this.items.length === 0;
134
+ }
135
+ /**
136
+ * Whether the batcher is waiting for the timeout to trigger batch processing
137
+ */
138
+ get isPending() {
139
+ return this._isPending;
140
+ }
141
+ getWait() {
142
+ if (typeof this.options.wait === "function") return this.options.wait(this);
143
+ return this.options.wait;
144
+ }
145
+ };
146
+ /**
147
+ * Creates a batcher that processes items in batches.
148
+ *
149
+ * This is an alternative to the batch function in the core @tanstack/pacer package, but is more
150
+ * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
151
+ * this function creates a batcher with no external dependencies, devtools integration, or reactive state.
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * const batchItems = liteBatch<number>(
156
+ * (items) => console.log('Processing:', items),
157
+ * {
158
+ * maxSize: 3,
159
+ * }
160
+ * );
161
+ *
162
+ * batchItems(1);
163
+ * batchItems(2);
164
+ * batchItems(3); // Triggers batch processing
165
+ * ```
166
+ */
167
+ function liteBatch(fn, options = {}) {
168
+ return new LiteBatcher(fn, options).addItem;
169
+ }
170
+
171
+ //#endregion
172
+ export { LiteBatcher, liteBatch };
173
+ //# sourceMappingURL=lite-batcher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-batcher.js","names":["fn: (items: Array<TValue>) => void","options: LiteBatcherOptions<TValue>"],"sources":["../src/lite-batcher.ts"],"sourcesContent":["/**\n * Options for configuring a lite batcher instance\n */\nexport interface LiteBatcherOptions<TValue> {\n /**\n * Custom function to determine if a batch should be processed\n * Return true to process the batch immediately\n */\n getShouldExecute?: (\n items: Array<TValue>,\n batcher: LiteBatcher<TValue>,\n ) => boolean\n /**\n * Maximum number of items in a batch\n * @default Infinity\n */\n maxSize?: number\n /**\n * Callback fired after a batch is processed\n */\n onExecute?: (batch: Array<TValue>, batcher: LiteBatcher<TValue>) => void\n /**\n * Callback fired after items are added to the batcher\n */\n onItemsChange?: (batcher: LiteBatcher<TValue>) => void\n /**\n * Whether the batcher should start processing immediately\n * @default true\n */\n started?: boolean\n /**\n * Maximum time in milliseconds to wait before processing a batch.\n * If the wait duration has elapsed, the batch will be processed.\n * If not provided, the batch will not be triggered by a timeout.\n * @default Infinity\n */\n wait?: number | ((batcher: LiteBatcher<TValue>) => number)\n}\n\n/**\n * A lightweight class that collects items and processes them in batches.\n *\n * This is an alternative to the Batcher in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core Batcher,\n * this version does not use TanStack Store for state management, has no devtools integration,\n * no callbacks, and provides only essential batching functionality.\n *\n * Batching is a technique for grouping multiple operations together to be processed as a single unit.\n * This synchronous version is lighter weight and often all you need.\n *\n * The Batcher provides a flexible way to implement batching with configurable:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * Features included:\n * - Core batching functionality (addItem, flush, clear, cancel)\n * - Size-based batching (maxSize)\n * - Time-based batching (wait timeout)\n * - Custom condition batching (getShouldExecute)\n * - Manual processing controls\n * - Public mutable options\n * - Callback support for monitoring batch execution and state changes\n *\n * Features NOT included (compared to core Batcher):\n * - No TanStack Store state management\n * - No devtools integration\n * - No complex state tracking (execution counts, etc.)\n * - No reactive state management\n *\n * @example\n * ```ts\n * // Basic batching\n * const batcher = new LiteBatcher<number>(\n * (items) => console.log('Processing batch:', items),\n * {\n * maxSize: 5,\n * wait: 2000,\n * onExecute: (batch, batcher) => {\n * console.log('Batch executed with', batch.length, 'items');\n * },\n * onItemsChange: (batcher) => {\n * console.log('Batch size changed to:', batcher.size);\n * }\n * }\n * );\n *\n * batcher.addItem(1);\n * batcher.addItem(2);\n * // After 2 seconds or when 5 items are added, whichever comes first,\n * // the batch will be processed\n * ```\n *\n * @example\n * ```ts\n * // Custom condition batching\n * const batcher = new LiteBatcher<Task>(\n * (items) => processTasks(items),\n * {\n * getShouldExecute: (items) => items.some(task => task.urgent),\n * maxSize: 10,\n * }\n * );\n *\n * batcher.addItem({ name: 'normal', urgent: false });\n * batcher.addItem({ name: 'urgent', urgent: true }); // Triggers immediate processing\n * ```\n */\nexport class LiteBatcher<TValue> {\n private items: Array<TValue> = []\n private timeoutId: NodeJS.Timeout | null = null\n private _isPending = false\n\n constructor(\n public fn: (items: Array<TValue>) => void,\n public options: LiteBatcherOptions<TValue> = {},\n ) {\n // Set defaults\n this.options.maxSize = this.options.maxSize ?? Infinity\n this.options.started = this.options.started ?? true\n this.options.wait = this.options.wait ?? Infinity\n this.options.getShouldExecute =\n this.options.getShouldExecute ?? (() => false)\n }\n\n /**\n * Number of items currently in the batch\n */\n get size(): number {\n return this.items.length\n }\n\n /**\n * Whether the batch has no items to process (items array is empty)\n */\n get isEmpty(): boolean {\n return this.items.length === 0\n }\n\n /**\n * Whether the batcher is waiting for the timeout to trigger batch processing\n */\n get isPending(): boolean {\n return this._isPending\n }\n\n private getWait(): number {\n if (typeof this.options.wait === 'function') {\n return this.options.wait(this)\n }\n return this.options.wait!\n }\n\n /**\n * Adds an item to the batcher\n * If the batch size is reached, timeout occurs, or getShouldExecute returns true, the batch will be processed\n */\n addItem = (item: TValue): void => {\n this.items.push(item)\n this._isPending = this.options.wait !== Infinity\n this.options.onItemsChange?.(this)\n\n const shouldProcess =\n this.items.length >= this.options.maxSize! ||\n this.options.getShouldExecute!(this.items, this)\n\n if (shouldProcess) {\n this.execute()\n } else if (this.options.wait !== Infinity) {\n this.clearTimeout() // clear any pending timeout to replace it with a new one\n this.timeoutId = setTimeout(() => this.execute(), this.getWait())\n }\n }\n\n /**\n * Processes the current batch of items.\n * This method will automatically be triggered if the batcher is running and any of these conditions are met:\n * - The number of items reaches maxSize\n * - The wait duration has elapsed\n * - The getShouldExecute function returns true upon adding an item\n *\n * You can also call this method manually to process the current batch at any time.\n */\n private execute = (): void => {\n if (this.items.length === 0) {\n return\n }\n\n const batch = this.peekAllItems() // copy of the items to be processed (to prevent race conditions)\n this.clear() // Clear items before processing to prevent race conditions\n\n this.fn(batch) // EXECUTE\n this.options.onExecute?.(batch, this)\n }\n\n /**\n * Processes the current batch of items immediately\n */\n flush = (): void => {\n this.clearTimeout() // clear any pending timeout\n this.execute() // execute immediately\n }\n\n /**\n * Returns a copy of all items in the batcher\n */\n peekAllItems = (): Array<TValue> => {\n return [...this.items]\n }\n\n private clearTimeout = (): void => {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = null\n }\n }\n\n /**\n * Removes all items from the batcher\n */\n clear = (): void => {\n const hadItems = this.items.length > 0\n this.items = []\n this._isPending = false\n if (hadItems) {\n this.options.onItemsChange?.(this)\n }\n }\n\n /**\n * Cancels any pending execution that was scheduled.\n * Does NOT clear out the items.\n */\n cancel = (): void => {\n this.clearTimeout()\n this._isPending = false\n }\n}\n\n/**\n * Creates a batcher that processes items in batches.\n *\n * This is an alternative to the batch function in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,\n * this function creates a batcher with no external dependencies, devtools integration, or reactive state.\n *\n * @example\n * ```ts\n * const batchItems = liteBatch<number>(\n * (items) => console.log('Processing:', items),\n * {\n * maxSize: 3,\n * }\n * );\n *\n * batchItems(1);\n * batchItems(2);\n * batchItems(3); // Triggers batch processing\n * ```\n */\nexport function liteBatch<TValue>(\n fn: (items: Array<TValue>) => void,\n options: LiteBatcherOptions<TValue> = {},\n): (item: TValue) => void {\n const batcher = new LiteBatcher<TValue>(fn, options)\n return batcher.addItem\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,IAAa,cAAb,MAAiC;CAK/B,YACE,AAAOA,IACP,AAAOC,UAAsC,EAAE,EAC/C;EAFO;EACA;eANsB,EAAE;mBACU;oBACtB;kBA8CV,SAAuB;AAChC,QAAK,MAAM,KAAK,KAAK;AACrB,QAAK,aAAa,KAAK,QAAQ,SAAS;AACxC,QAAK,QAAQ,gBAAgB,KAAK;AAMlC,OAHE,KAAK,MAAM,UAAU,KAAK,QAAQ,WAClC,KAAK,QAAQ,iBAAkB,KAAK,OAAO,KAAK,CAGhD,MAAK,SAAS;YACL,KAAK,QAAQ,SAAS,UAAU;AACzC,SAAK,cAAc;AACnB,SAAK,YAAY,iBAAiB,KAAK,SAAS,EAAE,KAAK,SAAS,CAAC;;;uBAavC;AAC5B,OAAI,KAAK,MAAM,WAAW,EACxB;GAGF,MAAM,QAAQ,KAAK,cAAc;AACjC,QAAK,OAAO;AAEZ,QAAK,GAAG,MAAM;AACd,QAAK,QAAQ,YAAY,OAAO,KAAK;;qBAMnB;AAClB,QAAK,cAAc;AACnB,QAAK,SAAS;;4BAMoB;AAClC,UAAO,CAAC,GAAG,KAAK,MAAM;;4BAGW;AACjC,OAAI,KAAK,WAAW;AAClB,iBAAa,KAAK,UAAU;AAC5B,SAAK,YAAY;;;qBAOD;GAClB,MAAM,WAAW,KAAK,MAAM,SAAS;AACrC,QAAK,QAAQ,EAAE;AACf,QAAK,aAAa;AAClB,OAAI,SACF,MAAK,QAAQ,gBAAgB,KAAK;;sBAQjB;AACnB,QAAK,cAAc;AACnB,QAAK,aAAa;;AArHlB,OAAK,QAAQ,UAAU,KAAK,QAAQ,WAAW;AAC/C,OAAK,QAAQ,UAAU,KAAK,QAAQ,WAAW;AAC/C,OAAK,QAAQ,OAAO,KAAK,QAAQ,QAAQ;AACzC,OAAK,QAAQ,mBACX,KAAK,QAAQ,2BAA2B;;;;;CAM5C,IAAI,OAAe;AACjB,SAAO,KAAK,MAAM;;;;;CAMpB,IAAI,UAAmB;AACrB,SAAO,KAAK,MAAM,WAAW;;;;;CAM/B,IAAI,YAAqB;AACvB,SAAO,KAAK;;CAGd,AAAQ,UAAkB;AACxB,MAAI,OAAO,KAAK,QAAQ,SAAS,WAC/B,QAAO,KAAK,QAAQ,KAAK,KAAK;AAEhC,SAAO,KAAK,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;AA8GxB,SAAgB,UACd,IACA,UAAsC,EAAE,EAChB;AAExB,QADgB,IAAI,YAAoB,IAAI,QAAQ,CACrC"}
@@ -0,0 +1,125 @@
1
+
2
+ //#region src/lite-debouncer.ts
3
+ /**
4
+ * A lightweight class that creates a debounced function.
5
+ *
6
+ * This is an alternative to the Debouncer in the core @tanstack/pacer package, but is more
7
+ * suitable for libraries and npm packages that need minimal overhead. Unlike the core Debouncer,
8
+ * this version does not use TanStack Store for state management, has no devtools integration,
9
+ * and provides only essential debouncing functionality.
10
+ *
11
+ * Debouncing ensures that a function is only executed after a certain amount of time has passed
12
+ * since its last invocation. This is useful for handling frequent events like window resizing,
13
+ * scroll events, or input changes where you want to limit the rate of execution.
14
+ *
15
+ * The debounced function can be configured to execute either at the start of the delay period
16
+ * (leading edge) or at the end (trailing edge, default). Each new call during the wait period
17
+ * will reset the timer.
18
+ *
19
+ * Features:
20
+ * - Zero dependencies - no external libraries required
21
+ * - Minimal API surface - only essential methods (maybeExecute, flush, cancel)
22
+ * - Simple state management - uses basic private properties instead of reactive stores
23
+ * - Callback support for monitoring execution events
24
+ * - Lightweight - designed for use in npm packages where bundle size matters
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * const debouncer = new LiteDebouncer((value: string) => {
29
+ * saveToDatabase(value);
30
+ * }, {
31
+ * wait: 500,
32
+ * onExecute: (args, debouncer) => {
33
+ * console.log('Saved value:', args[0]);
34
+ * }
35
+ * });
36
+ *
37
+ * // Will only save after 500ms of no new input
38
+ * inputElement.addEventListener('input', () => {
39
+ * debouncer.maybeExecute(inputElement.value);
40
+ * });
41
+ * ```
42
+ */
43
+ var LiteDebouncer = class {
44
+ constructor(fn, options) {
45
+ this.fn = fn;
46
+ this.options = options;
47
+ this.canLeadingExecute = true;
48
+ this.maybeExecute = (...args) => {
49
+ let didLeadingExecute = false;
50
+ if (this.options.leading && this.canLeadingExecute) {
51
+ this.canLeadingExecute = false;
52
+ didLeadingExecute = true;
53
+ this.fn(...args);
54
+ this.options.onExecute?.(args, this);
55
+ }
56
+ this.lastArgs = args;
57
+ if (this.timeoutId) clearTimeout(this.timeoutId);
58
+ this.timeoutId = setTimeout(() => {
59
+ this.canLeadingExecute = true;
60
+ if (this.options.trailing && !didLeadingExecute && this.lastArgs) {
61
+ this.fn(...this.lastArgs);
62
+ this.options.onExecute?.(this.lastArgs, this);
63
+ }
64
+ this.lastArgs = void 0;
65
+ }, this.options.wait);
66
+ };
67
+ this.flush = () => {
68
+ if (this.timeoutId && this.lastArgs) {
69
+ clearTimeout(this.timeoutId);
70
+ this.timeoutId = void 0;
71
+ const args = this.lastArgs;
72
+ this.fn(...args);
73
+ this.options.onExecute?.(args, this);
74
+ this.lastArgs = void 0;
75
+ this.canLeadingExecute = true;
76
+ }
77
+ };
78
+ this.cancel = () => {
79
+ if (this.timeoutId) {
80
+ clearTimeout(this.timeoutId);
81
+ this.timeoutId = void 0;
82
+ }
83
+ this.lastArgs = void 0;
84
+ this.canLeadingExecute = true;
85
+ };
86
+ if (this.options.leading === void 0 && this.options.trailing === void 0) this.options.trailing = true;
87
+ }
88
+ };
89
+ /**
90
+ * Creates a lightweight debounced function that delays invoking the provided function until after a specified wait time.
91
+ * Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
92
+ *
93
+ * This is an alternative to the debounce function in the core @tanstack/pacer package, but is more
94
+ * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
95
+ * this function creates a debouncer with no external dependencies, devtools integration, or reactive state.
96
+ *
97
+ * If leading option is true, the function will execute immediately on the first call, then wait the delay
98
+ * before allowing another execution.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const debouncedSave = liteDebounce(() => {
103
+ * saveChanges();
104
+ * }, { wait: 1000 });
105
+ *
106
+ * // Called repeatedly but executes at most once per second
107
+ * inputElement.addEventListener('input', debouncedSave);
108
+ * ```
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * // Leading edge execution - fires immediately then waits
113
+ * const debouncedSearch = liteDebounce((query: string) => {
114
+ * performSearch(query);
115
+ * }, { wait: 300, leading: true });
116
+ * ```
117
+ */
118
+ function liteDebounce(fn, options) {
119
+ return new LiteDebouncer(fn, options).maybeExecute;
120
+ }
121
+
122
+ //#endregion
123
+ exports.LiteDebouncer = LiteDebouncer;
124
+ exports.liteDebounce = liteDebounce;
125
+ //# sourceMappingURL=lite-debouncer.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-debouncer.cjs","names":["fn: TFn","options: LiteDebouncerOptions<TFn>"],"sources":["../src/lite-debouncer.ts"],"sourcesContent":["import type { AnyFunction } from '@tanstack/pacer/types'\n\n/**\n * Options for configuring a lite debounced function\n */\nexport interface LiteDebouncerOptions<TFn extends AnyFunction = AnyFunction> {\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?: (args: Parameters<TFn>, debouncer: LiteDebouncer<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 */\n wait: number\n}\n\n/**\n * A lightweight class that creates a debounced function.\n *\n * This is an alternative to the Debouncer in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core Debouncer,\n * this version does not use TanStack Store for state management, has no devtools integration,\n * and provides only essential debouncing functionality.\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 * Features:\n * - Zero dependencies - no external libraries required\n * - Minimal API surface - only essential methods (maybeExecute, flush, cancel)\n * - Simple state management - uses basic private properties instead of reactive stores\n * - Callback support for monitoring execution events\n * - Lightweight - designed for use in npm packages where bundle size matters\n *\n * @example\n * ```ts\n * const debouncer = new LiteDebouncer((value: string) => {\n * saveToDatabase(value);\n * }, {\n * wait: 500,\n * onExecute: (args, debouncer) => {\n * console.log('Saved value:', args[0]);\n * }\n * });\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 LiteDebouncer<TFn extends AnyFunction> {\n private timeoutId: NodeJS.Timeout | undefined\n private lastArgs: Parameters<TFn> | undefined\n private canLeadingExecute = true\n\n constructor(\n public fn: TFn,\n public options: LiteDebouncerOptions<TFn>,\n ) {\n // Default trailing to true if neither leading nor trailing is specified\n if (\n this.options.leading === undefined &&\n this.options.trailing === undefined\n ) {\n this.options.trailing = true\n }\n }\n\n /**\n * Attempts to execute the debounced function.\n * If leading is true and this is the first call, executes immediately.\n * Otherwise, queues the execution for after the wait time.\n * Each new call resets the timer.\n */\n maybeExecute = (...args: Parameters<TFn>): void => {\n let didLeadingExecute = false\n\n if (this.options.leading && this.canLeadingExecute) {\n this.canLeadingExecute = false\n didLeadingExecute = true\n this.fn(...args)\n this.options.onExecute?.(args, this)\n }\n\n this.lastArgs = args\n\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n }\n\n this.timeoutId = setTimeout(() => {\n this.canLeadingExecute = true\n if (this.options.trailing && !didLeadingExecute && this.lastArgs) {\n this.fn(...this.lastArgs)\n this.options.onExecute?.(this.lastArgs, this)\n }\n this.lastArgs = undefined\n }, this.options.wait)\n }\n\n /**\n * Processes the current pending execution immediately.\n * If there's a pending execution, it will be executed right away\n * and the timeout will be cleared.\n */\n flush = (): void => {\n if (this.timeoutId && this.lastArgs) {\n clearTimeout(this.timeoutId)\n this.timeoutId = undefined\n const args = this.lastArgs\n this.fn(...args)\n this.options.onExecute?.(args, this)\n this.lastArgs = undefined\n this.canLeadingExecute = true\n }\n }\n\n /**\n * Cancels any pending execution.\n * Clears the timeout and resets the internal state.\n */\n cancel = (): void => {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId)\n this.timeoutId = undefined\n }\n this.lastArgs = undefined\n this.canLeadingExecute = true\n }\n}\n\n/**\n * Creates a lightweight 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 is an alternative to the debounce function in the core @tanstack/pacer package, but is more\n * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,\n * this function creates a debouncer with no external dependencies, devtools integration, or reactive state.\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 debouncedSave = liteDebounce(() => {\n * saveChanges();\n * }, { wait: 1000 });\n *\n * // Called repeatedly but executes at most once per second\n * inputElement.addEventListener('input', debouncedSave);\n * ```\n *\n * @example\n * ```ts\n * // Leading edge execution - fires immediately then waits\n * const debouncedSearch = liteDebounce((query: string) => {\n * performSearch(query);\n * }, { wait: 300, leading: true });\n * ```\n */\nexport function liteDebounce<TFn extends AnyFunction>(\n fn: TFn,\n options: LiteDebouncerOptions<TFn>,\n): (...args: Parameters<TFn>) => void {\n const debouncer = new LiteDebouncer(fn, options)\n return debouncer.maybeExecute\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,IAAa,gBAAb,MAAoD;CAKlD,YACE,AAAOA,IACP,AAAOC,SACP;EAFO;EACA;2BAJmB;uBAqBZ,GAAG,SAAgC;GACjD,IAAI,oBAAoB;AAExB,OAAI,KAAK,QAAQ,WAAW,KAAK,mBAAmB;AAClD,SAAK,oBAAoB;AACzB,wBAAoB;AACpB,SAAK,GAAG,GAAG,KAAK;AAChB,SAAK,QAAQ,YAAY,MAAM,KAAK;;AAGtC,QAAK,WAAW;AAEhB,OAAI,KAAK,UACP,cAAa,KAAK,UAAU;AAG9B,QAAK,YAAY,iBAAiB;AAChC,SAAK,oBAAoB;AACzB,QAAI,KAAK,QAAQ,YAAY,CAAC,qBAAqB,KAAK,UAAU;AAChE,UAAK,GAAG,GAAG,KAAK,SAAS;AACzB,UAAK,QAAQ,YAAY,KAAK,UAAU,KAAK;;AAE/C,SAAK,WAAW;MACf,KAAK,QAAQ,KAAK;;qBAQH;AAClB,OAAI,KAAK,aAAa,KAAK,UAAU;AACnC,iBAAa,KAAK,UAAU;AAC5B,SAAK,YAAY;IACjB,MAAM,OAAO,KAAK;AAClB,SAAK,GAAG,GAAG,KAAK;AAChB,SAAK,QAAQ,YAAY,MAAM,KAAK;AACpC,SAAK,WAAW;AAChB,SAAK,oBAAoB;;;sBAQR;AACnB,OAAI,KAAK,WAAW;AAClB,iBAAa,KAAK,UAAU;AAC5B,SAAK,YAAY;;AAEnB,QAAK,WAAW;AAChB,QAAK,oBAAoB;;AAnEzB,MACE,KAAK,QAAQ,YAAY,UACzB,KAAK,QAAQ,aAAa,OAE1B,MAAK,QAAQ,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgG9B,SAAgB,aACd,IACA,SACoC;AAEpC,QADkB,IAAI,cAAc,IAAI,QAAQ,CAC/B"}
@@ -1,27 +1,30 @@
1
- import { AnyFunction } from '@tanstack/pacer/types';
1
+ import { AnyFunction } from "@tanstack/pacer/types";
2
+
3
+ //#region src/lite-debouncer.d.ts
4
+
2
5
  /**
3
6
  * Options for configuring a lite debounced function
4
7
  */
5
- export interface LiteDebouncerOptions<TFn extends AnyFunction = AnyFunction> {
6
- /**
7
- * Whether to execute on the leading edge of the timeout.
8
- * The first call will execute immediately and the rest will wait the delay.
9
- * Defaults to false.
10
- */
11
- leading?: boolean;
12
- /**
13
- * Callback function that is called after the function is executed
14
- */
15
- onExecute?: (args: Parameters<TFn>, debouncer: LiteDebouncer<TFn>) => void;
16
- /**
17
- * Whether to execute on the trailing edge of the timeout.
18
- * Defaults to true.
19
- */
20
- trailing?: boolean;
21
- /**
22
- * Delay in milliseconds before executing the function.
23
- */
24
- wait: number;
8
+ interface LiteDebouncerOptions<TFn extends AnyFunction = AnyFunction> {
9
+ /**
10
+ * Whether to execute on the leading edge of the timeout.
11
+ * The first call will execute immediately and the rest will wait the delay.
12
+ * Defaults to false.
13
+ */
14
+ leading?: boolean;
15
+ /**
16
+ * Callback function that is called after the function is executed
17
+ */
18
+ onExecute?: (args: Parameters<TFn>, debouncer: LiteDebouncer<TFn>) => void;
19
+ /**
20
+ * Whether to execute on the trailing edge of the timeout.
21
+ * Defaults to true.
22
+ */
23
+ trailing?: boolean;
24
+ /**
25
+ * Delay in milliseconds before executing the function.
26
+ */
27
+ wait: number;
25
28
  }
26
29
  /**
27
30
  * A lightweight class that creates a debounced function.
@@ -63,31 +66,31 @@ export interface LiteDebouncerOptions<TFn extends AnyFunction = AnyFunction> {
63
66
  * });
64
67
  * ```
65
68
  */
66
- export declare class LiteDebouncer<TFn extends AnyFunction> {
67
- fn: TFn;
68
- options: LiteDebouncerOptions<TFn>;
69
- private timeoutId;
70
- private lastArgs;
71
- private canLeadingExecute;
72
- constructor(fn: TFn, options: LiteDebouncerOptions<TFn>);
73
- /**
74
- * Attempts to execute the debounced function.
75
- * If leading is true and this is the first call, executes immediately.
76
- * Otherwise, queues the execution for after the wait time.
77
- * Each new call resets the timer.
78
- */
79
- maybeExecute: (...args: Parameters<TFn>) => void;
80
- /**
81
- * Processes the current pending execution immediately.
82
- * If there's a pending execution, it will be executed right away
83
- * and the timeout will be cleared.
84
- */
85
- flush: () => void;
86
- /**
87
- * Cancels any pending execution.
88
- * Clears the timeout and resets the internal state.
89
- */
90
- cancel: () => void;
69
+ declare class LiteDebouncer<TFn extends AnyFunction> {
70
+ fn: TFn;
71
+ options: LiteDebouncerOptions<TFn>;
72
+ private timeoutId;
73
+ private lastArgs;
74
+ private canLeadingExecute;
75
+ constructor(fn: TFn, options: LiteDebouncerOptions<TFn>);
76
+ /**
77
+ * Attempts to execute the debounced function.
78
+ * If leading is true and this is the first call, executes immediately.
79
+ * Otherwise, queues the execution for after the wait time.
80
+ * Each new call resets the timer.
81
+ */
82
+ maybeExecute: (...args: Parameters<TFn>) => void;
83
+ /**
84
+ * Processes the current pending execution immediately.
85
+ * If there's a pending execution, it will be executed right away
86
+ * and the timeout will be cleared.
87
+ */
88
+ flush: () => void;
89
+ /**
90
+ * Cancels any pending execution.
91
+ * Clears the timeout and resets the internal state.
92
+ */
93
+ cancel: () => void;
91
94
  }
92
95
  /**
93
96
  * Creates a lightweight debounced function that delays invoking the provided function until after a specified wait time.
@@ -118,4 +121,7 @@ export declare class LiteDebouncer<TFn extends AnyFunction> {
118
121
  * }, { wait: 300, leading: true });
119
122
  * ```
120
123
  */
121
- export declare function liteDebounce<TFn extends AnyFunction>(fn: TFn, options: LiteDebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
124
+ declare function liteDebounce<TFn extends AnyFunction>(fn: TFn, options: LiteDebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
125
+ //#endregion
126
+ export { LiteDebouncer, LiteDebouncerOptions, liteDebounce };
127
+ //# sourceMappingURL=lite-debouncer.d.cts.map
@@ -1,27 +1,30 @@
1
- import { AnyFunction } from '@tanstack/pacer/types';
1
+ import { AnyFunction } from "@tanstack/pacer/types";
2
+
3
+ //#region src/lite-debouncer.d.ts
4
+
2
5
  /**
3
6
  * Options for configuring a lite debounced function
4
7
  */
5
- export interface LiteDebouncerOptions<TFn extends AnyFunction = AnyFunction> {
6
- /**
7
- * Whether to execute on the leading edge of the timeout.
8
- * The first call will execute immediately and the rest will wait the delay.
9
- * Defaults to false.
10
- */
11
- leading?: boolean;
12
- /**
13
- * Callback function that is called after the function is executed
14
- */
15
- onExecute?: (args: Parameters<TFn>, debouncer: LiteDebouncer<TFn>) => void;
16
- /**
17
- * Whether to execute on the trailing edge of the timeout.
18
- * Defaults to true.
19
- */
20
- trailing?: boolean;
21
- /**
22
- * Delay in milliseconds before executing the function.
23
- */
24
- wait: number;
8
+ interface LiteDebouncerOptions<TFn extends AnyFunction = AnyFunction> {
9
+ /**
10
+ * Whether to execute on the leading edge of the timeout.
11
+ * The first call will execute immediately and the rest will wait the delay.
12
+ * Defaults to false.
13
+ */
14
+ leading?: boolean;
15
+ /**
16
+ * Callback function that is called after the function is executed
17
+ */
18
+ onExecute?: (args: Parameters<TFn>, debouncer: LiteDebouncer<TFn>) => void;
19
+ /**
20
+ * Whether to execute on the trailing edge of the timeout.
21
+ * Defaults to true.
22
+ */
23
+ trailing?: boolean;
24
+ /**
25
+ * Delay in milliseconds before executing the function.
26
+ */
27
+ wait: number;
25
28
  }
26
29
  /**
27
30
  * A lightweight class that creates a debounced function.
@@ -63,31 +66,31 @@ export interface LiteDebouncerOptions<TFn extends AnyFunction = AnyFunction> {
63
66
  * });
64
67
  * ```
65
68
  */
66
- export declare class LiteDebouncer<TFn extends AnyFunction> {
67
- fn: TFn;
68
- options: LiteDebouncerOptions<TFn>;
69
- private timeoutId;
70
- private lastArgs;
71
- private canLeadingExecute;
72
- constructor(fn: TFn, options: LiteDebouncerOptions<TFn>);
73
- /**
74
- * Attempts to execute the debounced function.
75
- * If leading is true and this is the first call, executes immediately.
76
- * Otherwise, queues the execution for after the wait time.
77
- * Each new call resets the timer.
78
- */
79
- maybeExecute: (...args: Parameters<TFn>) => void;
80
- /**
81
- * Processes the current pending execution immediately.
82
- * If there's a pending execution, it will be executed right away
83
- * and the timeout will be cleared.
84
- */
85
- flush: () => void;
86
- /**
87
- * Cancels any pending execution.
88
- * Clears the timeout and resets the internal state.
89
- */
90
- cancel: () => void;
69
+ declare class LiteDebouncer<TFn extends AnyFunction> {
70
+ fn: TFn;
71
+ options: LiteDebouncerOptions<TFn>;
72
+ private timeoutId;
73
+ private lastArgs;
74
+ private canLeadingExecute;
75
+ constructor(fn: TFn, options: LiteDebouncerOptions<TFn>);
76
+ /**
77
+ * Attempts to execute the debounced function.
78
+ * If leading is true and this is the first call, executes immediately.
79
+ * Otherwise, queues the execution for after the wait time.
80
+ * Each new call resets the timer.
81
+ */
82
+ maybeExecute: (...args: Parameters<TFn>) => void;
83
+ /**
84
+ * Processes the current pending execution immediately.
85
+ * If there's a pending execution, it will be executed right away
86
+ * and the timeout will be cleared.
87
+ */
88
+ flush: () => void;
89
+ /**
90
+ * Cancels any pending execution.
91
+ * Clears the timeout and resets the internal state.
92
+ */
93
+ cancel: () => void;
91
94
  }
92
95
  /**
93
96
  * Creates a lightweight debounced function that delays invoking the provided function until after a specified wait time.
@@ -118,4 +121,7 @@ export declare class LiteDebouncer<TFn extends AnyFunction> {
118
121
  * }, { wait: 300, leading: true });
119
122
  * ```
120
123
  */
121
- export declare function liteDebounce<TFn extends AnyFunction>(fn: TFn, options: LiteDebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
124
+ declare function liteDebounce<TFn extends AnyFunction>(fn: TFn, options: LiteDebouncerOptions<TFn>): (...args: Parameters<TFn>) => void;
125
+ //#endregion
126
+ export { LiteDebouncer, LiteDebouncerOptions, liteDebounce };
127
+ //# sourceMappingURL=lite-debouncer.d.ts.map