@develia/commons 0.4.23 → 0.4.24

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 (46) hide show
  1. package/dist/cjs/debouncer.js +121 -0
  2. package/dist/cjs/debouncer.js.map +1 -0
  3. package/dist/cjs/functions.js +0 -86
  4. package/dist/cjs/functions.js.map +1 -1
  5. package/dist/cjs/index.js +5 -1
  6. package/dist/cjs/index.js.map +1 -1
  7. package/dist/cjs/keyed-debouncer.js +144 -0
  8. package/dist/cjs/keyed-debouncer.js.map +1 -0
  9. package/dist/cjs/utilities.js +27 -4
  10. package/dist/cjs/utilities.js.map +1 -1
  11. package/dist/esm/debouncer.js +118 -0
  12. package/dist/esm/debouncer.js.map +1 -0
  13. package/dist/esm/functions.js +0 -85
  14. package/dist/esm/functions.js.map +1 -1
  15. package/dist/esm/index.js +2 -0
  16. package/dist/esm/index.js.map +1 -1
  17. package/dist/esm/keyed-debouncer.js +109 -0
  18. package/dist/esm/keyed-debouncer.js.map +1 -0
  19. package/dist/esm/utilities.js +27 -4
  20. package/dist/esm/utilities.js.map +1 -1
  21. package/dist/types/debouncer.d.ts +60 -0
  22. package/dist/types/debouncer.d.ts.map +1 -0
  23. package/dist/types/functions.d.ts +5 -35
  24. package/dist/types/functions.d.ts.map +1 -1
  25. package/dist/types/index.d.ts +4 -0
  26. package/dist/types/index.d.ts.map +1 -1
  27. package/dist/types/keyed-debouncer.d.ts +56 -0
  28. package/dist/types/keyed-debouncer.d.ts.map +1 -0
  29. package/dist/types/utilities.d.ts +8 -3
  30. package/dist/types/utilities.d.ts.map +1 -1
  31. package/dist/web/debouncer.js +118 -0
  32. package/dist/web/debouncer.js.map +1 -0
  33. package/dist/web/functions.js +0 -85
  34. package/dist/web/functions.js.map +1 -1
  35. package/dist/web/index.js +2 -0
  36. package/dist/web/index.js.map +1 -1
  37. package/dist/web/keyed-debouncer.js +109 -0
  38. package/dist/web/keyed-debouncer.js.map +1 -0
  39. package/dist/web/utilities.js +27 -4
  40. package/dist/web/utilities.js.map +1 -1
  41. package/package.json +1 -1
  42. package/src/debouncer.ts +135 -0
  43. package/src/functions.ts +5 -114
  44. package/src/index.ts +4 -0
  45. package/src/keyed-debouncer.ts +121 -0
  46. package/src/utilities.ts +30 -4
@@ -0,0 +1,118 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _Debouncer_instances, _Debouncer_controller, _Debouncer_delayMs, _Debouncer_onSchedule, _Debouncer_onStart, _Debouncer_onSuccess, _Debouncer_onCancel, _Debouncer_onError, _Debouncer_onIdle, _Debouncer_run, _Debouncer_becomeIdle;
13
+ import { delay } from "./utilities.js";
14
+ import { noop } from "./functions.js";
15
+ /**
16
+ * Keeps at most one live task.
17
+ * Scheduling a new task cancels the previous one, whether it was still
18
+ * waiting or already running.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const debouncer = new Debouncer({delayMs: 1500});
23
+ *
24
+ * debouncer.schedule(async (signal) => {
25
+ * const reply = await callAI(messages, {signal});
26
+ * if (signal.aborted) return;
27
+ * await sendReply(reply);
28
+ * });
29
+ * ```
30
+ */
31
+ class Debouncer {
32
+ constructor(options) {
33
+ _Debouncer_instances.add(this);
34
+ _Debouncer_controller.set(this, void 0);
35
+ _Debouncer_delayMs.set(this, void 0);
36
+ _Debouncer_onSchedule.set(this, void 0);
37
+ _Debouncer_onStart.set(this, void 0);
38
+ _Debouncer_onSuccess.set(this, void 0);
39
+ _Debouncer_onCancel.set(this, void 0);
40
+ _Debouncer_onError.set(this, void 0);
41
+ _Debouncer_onIdle.set(this, void 0);
42
+ assertValidDelay(options.delayMs);
43
+ __classPrivateFieldSet(this, _Debouncer_delayMs, options.delayMs, "f");
44
+ __classPrivateFieldSet(this, _Debouncer_onSchedule, options.onSchedule ?? noop, "f");
45
+ __classPrivateFieldSet(this, _Debouncer_onStart, options.onStart ?? noop, "f");
46
+ __classPrivateFieldSet(this, _Debouncer_onSuccess, options.onSuccess ?? noop, "f");
47
+ __classPrivateFieldSet(this, _Debouncer_onCancel, options.onCancel ?? noop, "f");
48
+ __classPrivateFieldSet(this, _Debouncer_onError, options.onError ?? console.error, "f");
49
+ __classPrivateFieldSet(this, _Debouncer_onIdle, options.onIdle ?? noop, "f");
50
+ }
51
+ /** Whether a task is waiting or running. */
52
+ get isPending() {
53
+ return __classPrivateFieldGet(this, _Debouncer_controller, "f") !== undefined;
54
+ }
55
+ /**
56
+ * Schedule `task`, cancelling any previous task.
57
+ *
58
+ * @param task - The task to run once the delay elapses.
59
+ * @param delayMs - Wait for this task only. Defaults to the configured `delayMs`.
60
+ */
61
+ schedule(task, delayMs = __classPrivateFieldGet(this, _Debouncer_delayMs, "f")) {
62
+ assertValidDelay(delayMs);
63
+ if (__classPrivateFieldGet(this, _Debouncer_controller, "f") !== undefined) {
64
+ __classPrivateFieldGet(this, _Debouncer_controller, "f").abort();
65
+ __classPrivateFieldGet(this, _Debouncer_onCancel, "f").call(this);
66
+ }
67
+ const controller = new AbortController();
68
+ __classPrivateFieldSet(this, _Debouncer_controller, controller, "f");
69
+ __classPrivateFieldGet(this, _Debouncer_onSchedule, "f").call(this);
70
+ void __classPrivateFieldGet(this, _Debouncer_instances, "m", _Debouncer_run).call(this, task, delayMs, controller);
71
+ }
72
+ /** Cancel the current task, if any. */
73
+ cancel() {
74
+ if (__classPrivateFieldGet(this, _Debouncer_controller, "f") === undefined) {
75
+ return;
76
+ }
77
+ __classPrivateFieldGet(this, _Debouncer_controller, "f").abort();
78
+ __classPrivateFieldGet(this, _Debouncer_onCancel, "f").call(this);
79
+ __classPrivateFieldGet(this, _Debouncer_instances, "m", _Debouncer_becomeIdle).call(this);
80
+ }
81
+ }
82
+ _Debouncer_controller = new WeakMap(), _Debouncer_delayMs = new WeakMap(), _Debouncer_onSchedule = new WeakMap(), _Debouncer_onStart = new WeakMap(), _Debouncer_onSuccess = new WeakMap(), _Debouncer_onCancel = new WeakMap(), _Debouncer_onError = new WeakMap(), _Debouncer_onIdle = new WeakMap(), _Debouncer_instances = new WeakSet(), _Debouncer_run = async function _Debouncer_run(task, delayMs, controller) {
83
+ const signal = controller.signal;
84
+ try {
85
+ await delay(delayMs, signal);
86
+ __classPrivateFieldGet(this, _Debouncer_onStart, "f").call(this);
87
+ await task(signal);
88
+ if (!signal.aborted) {
89
+ __classPrivateFieldGet(this, _Debouncer_onSuccess, "f").call(this);
90
+ }
91
+ }
92
+ catch (error) {
93
+ if (!signal.aborted) {
94
+ __classPrivateFieldGet(this, _Debouncer_onError, "f").call(this, error);
95
+ }
96
+ }
97
+ finally {
98
+ // A replaced or cancelled task must not touch the current state.
99
+ if (__classPrivateFieldGet(this, _Debouncer_controller, "f") === controller) {
100
+ __classPrivateFieldGet(this, _Debouncer_instances, "m", _Debouncer_becomeIdle).call(this);
101
+ }
102
+ }
103
+ }, _Debouncer_becomeIdle = function _Debouncer_becomeIdle() {
104
+ __classPrivateFieldSet(this, _Debouncer_controller, undefined, "f");
105
+ __classPrivateFieldGet(this, _Debouncer_onIdle, "f").call(this);
106
+ };
107
+ export default Debouncer;
108
+ /**
109
+ * Throw a `RangeError` unless `delayMs` is a finite number >= 0.
110
+ *
111
+ * @internal Shared with `KeyedDebouncer`; not part of the public API.
112
+ */
113
+ export function assertValidDelay(delayMs) {
114
+ if (!Number.isFinite(delayMs) || delayMs < 0) {
115
+ throw new RangeError(`delayMs must be a number >= 0 (received: ${delayMs})`);
116
+ }
117
+ }
118
+ //# sourceMappingURL=debouncer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debouncer.js","sourceRoot":"","sources":["../../src/debouncer.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAC,KAAK,EAAC,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAC,IAAI,EAAC,MAAM,gBAAgB,CAAC;AA0BpC;;;;;;;;;;;;;;;GAeG;AACH,MAAqB,SAAS;IAU1B,YAAY,OAAyB;;QATrC,wCAAyC;QAChC,qCAAiB;QACjB,wCAAwB;QACxB,qCAAqB;QACrB,uCAAuB;QACvB,sCAAsB;QACtB,qCAAmC;QACnC,oCAAoB;QAGzB,gBAAgB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAClC,uBAAA,IAAI,sBAAY,OAAO,CAAC,OAAO,MAAA,CAAC;QAChC,uBAAA,IAAI,yBAAe,OAAO,CAAC,UAAU,IAAI,IAAI,MAAA,CAAC;QAC9C,uBAAA,IAAI,sBAAY,OAAO,CAAC,OAAO,IAAI,IAAI,MAAA,CAAC;QACxC,uBAAA,IAAI,wBAAc,OAAO,CAAC,SAAS,IAAI,IAAI,MAAA,CAAC;QAC5C,uBAAA,IAAI,uBAAa,OAAO,CAAC,QAAQ,IAAI,IAAI,MAAA,CAAC;QAC1C,uBAAA,IAAI,sBAAY,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC,KAAK,MAAA,CAAC;QACjD,uBAAA,IAAI,qBAAW,OAAO,CAAC,MAAM,IAAI,IAAI,MAAA,CAAC;IAC1C,CAAC;IAED,4CAA4C;IAC5C,IAAI,SAAS;QACT,OAAO,uBAAA,IAAI,6BAAY,KAAK,SAAS,CAAC;IAC1C,CAAC;IAED;;;;;OAK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MAAM,CAAC,OAAO,EAAE,CAAC;YAClB,uBAAA,IAAI,0BAAS,MAAb,IAAI,EAAU,KAAK,CAAC,CAAC;QACzB,CAAC;IACL,CAAC;YAAS,CAAC;QACP,iEAAiE;QACjE,IAAI,uBAAA,IAAI,6BAAY,KAAK,UAAU,EAAE,CAAC;YAClC,uBAAA,IAAI,mDAAY,MAAhB,IAAI,CAAc,CAAC;QACvB,CAAC;IACL,CAAC;AACL,CAAC;IAGG,uBAAA,IAAI,yBAAe,SAAS,MAAA,CAAC;IAC7B,uBAAA,IAAI,yBAAQ,MAAZ,IAAI,CAAU,CAAC;AACnB,CAAC;eA/EgB,SAAS;AAkF9B;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAe;IAC5C,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,OAAO,GAAG,CAAC,EAAE,CAAC;QAC3C,MAAM,IAAI,UAAU,CAAC,4CAA4C,OAAO,GAAG,CAAC,CAAC;IACjF,CAAC;AACL,CAAC","sourcesContent":["import {delay} from \"./utilities.js\";\nimport {noop} from \"./functions.js\";\n\n/**\n * Cancellable task. It must honour `signal`: pass it to fetch/SDKs and check\n * `signal.aborted` before producing irreversible side effects.\n */\nexport type DebouncedTask = (signal: AbortSignal) => Promise<void>;\n\n/** Options accepted by {@link Debouncer}. */\nexport interface DebouncerOptions {\n /** Default wait, in milliseconds, before a task is executed. */\n delayMs: number;\n /** Called every time a task is scheduled, after any previous task has been cancelled. */\n onSchedule?: () => void;\n /** Called when the wait elapses and the task is about to run. */\n onStart?: () => void;\n /** Called when a task completes without throwing and without being cancelled. */\n onSuccess?: () => void;\n /** Called when a live task is cancelled, either by {@link Debouncer.cancel} or by being replaced. */\n onCancel?: () => void;\n /** Receives task errors. Cancellations never reach this callback. Defaults to `console.error`. */\n onError?: (error: unknown) => void;\n /** Called every time the debouncer goes from busy to idle. */\n onIdle?: () => void;\n}\n\n/**\n * Keeps at most one live task.\n * Scheduling a new task cancels the previous one, whether it was still\n * waiting or already running.\n *\n * @example\n * ```ts\n * const debouncer = new Debouncer({delayMs: 1500});\n *\n * debouncer.schedule(async (signal) => {\n * const reply = await callAI(messages, {signal});\n * if (signal.aborted) return;\n * await sendReply(reply);\n * });\n * ```\n */\nexport default class Debouncer {\n #controller: AbortController | undefined;\n readonly #delayMs: number;\n readonly #onSchedule: () => void;\n readonly #onStart: () => void;\n readonly #onSuccess: () => void;\n readonly #onCancel: () => void;\n readonly #onError: (error: unknown) => void;\n readonly #onIdle: () => void;\n\n constructor(options: DebouncerOptions) {\n assertValidDelay(options.delayMs);\n this.#delayMs = options.delayMs;\n this.#onSchedule = options.onSchedule ?? noop;\n this.#onStart = options.onStart ?? noop;\n this.#onSuccess = options.onSuccess ?? noop;\n this.#onCancel = options.onCancel ?? noop;\n this.#onError = options.onError ?? console.error;\n this.#onIdle = options.onIdle ?? noop;\n }\n\n /** Whether a task is waiting or running. */\n get isPending(): boolean {\n return this.#controller !== undefined;\n }\n\n /**\n * Schedule `task`, cancelling any previous task.\n *\n * @param task - The task to run once the delay elapses.\n * @param delayMs - Wait for this task only. Defaults to the configured `delayMs`.\n */\n schedule(task: DebouncedTask, delayMs: number = this.#delayMs): void {\n assertValidDelay(delayMs);\n if (this.#controller !== undefined) {\n this.#controller.abort();\n this.#onCancel();\n }\n\n const controller = new AbortController();\n this.#controller = controller;\n this.#onSchedule();\n void this.#run(task, delayMs, controller);\n }\n\n /** Cancel the current task, if any. */\n cancel(): void {\n if (this.#controller === undefined) {\n return;\n }\n this.#controller.abort();\n this.#onCancel();\n this.#becomeIdle();\n }\n\n async #run(task: DebouncedTask, delayMs: number, controller: AbortController): Promise<void> {\n const signal = controller.signal;\n try {\n await delay(delayMs, signal);\n this.#onStart();\n await task(signal);\n if (!signal.aborted) {\n this.#onSuccess();\n }\n } catch (error) {\n if (!signal.aborted) {\n this.#onError(error);\n }\n } finally {\n // A replaced or cancelled task must not touch the current state.\n if (this.#controller === controller) {\n this.#becomeIdle();\n }\n }\n }\n\n #becomeIdle(): void {\n this.#controller = undefined;\n this.#onIdle();\n }\n}\n\n/**\n * Throw a `RangeError` unless `delayMs` is a finite number >= 0.\n *\n * @internal Shared with `KeyedDebouncer`; not part of the public API.\n */\nexport function assertValidDelay(delayMs: number): void {\n if (!Number.isFinite(delayMs) || delayMs < 0) {\n throw new RangeError(`delayMs must be a number >= 0 (received: ${delayMs})`);\n }\n}\n"]}
@@ -113,91 +113,6 @@ export function memoize(fn, resolver, cache = new Map()) {
113
113
  memoized.has = (...args) => cache.has(resolveKey(...args));
114
114
  return memoized;
115
115
  }
116
- /**
117
- * Delay a function until no calls have been made for the configured wait time.
118
- * The latest arguments and this-context are used for the trailing execution.
119
- *
120
- * @example
121
- * ```ts
122
- * const search = debounce((query: string) => {
123
- * console.log(query);
124
- * }, 300);
125
- *
126
- * search("com");
127
- * search("commons"); // only this value is printed after 300 ms
128
- * ```
129
- *
130
- * @example
131
- * ```ts
132
- * const track = debounce(sendAnalytics, 1000, {leading: true, trailing: false});
133
- *
134
- * track("open"); // executed immediately
135
- * track.cancel(); // cancel the pending debounce window
136
- * ```
137
- */
138
- export function debounce(fn, wait, options = {}) {
139
- const delay = normalizeDelay(wait);
140
- const leading = options.leading ?? false;
141
- const trailing = options.trailing ?? true;
142
- let timer;
143
- let lastArgs;
144
- let lastThis;
145
- let result;
146
- const invoke = () => {
147
- const args = lastArgs;
148
- const context = lastThis;
149
- lastArgs = undefined;
150
- lastThis = undefined;
151
- result = fn.apply(context, args);
152
- return result;
153
- };
154
- const expire = () => {
155
- timer = undefined;
156
- if (trailing && lastArgs) {
157
- invoke();
158
- }
159
- else {
160
- lastArgs = undefined;
161
- lastThis = undefined;
162
- }
163
- };
164
- const start = () => {
165
- timer = setTimeout(expire, delay);
166
- };
167
- const debounced = function (...args) {
168
- const invokeLeading = leading && timer === undefined;
169
- lastArgs = args;
170
- lastThis = this;
171
- if (timer !== undefined) {
172
- clearTimeout(timer);
173
- }
174
- start();
175
- if (invokeLeading) {
176
- return invoke();
177
- }
178
- return result;
179
- };
180
- debounced.cancel = () => {
181
- if (timer !== undefined) {
182
- clearTimeout(timer);
183
- }
184
- timer = undefined;
185
- lastArgs = undefined;
186
- lastThis = undefined;
187
- };
188
- debounced.flush = () => {
189
- if (timer !== undefined) {
190
- clearTimeout(timer);
191
- timer = undefined;
192
- if (lastArgs && trailing) {
193
- return invoke();
194
- }
195
- }
196
- return result;
197
- };
198
- debounced.pending = () => timer !== undefined;
199
- return debounced;
200
- }
201
116
  /**
202
117
  * Limit how often a function can run during a time window.
203
118
  * Calls made while the function is throttled can optionally be replayed once at the end with the latest arguments.
@@ -1 +1 @@
1
- {"version":3,"file":"functions.js","sourceRoot":"","sources":["../../src/functions.ts"],"names":[],"mappings":"AAwEA;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,QAAQ,CAAI,KAAQ;IAChC,OAAO,KAAK,CAAC;AACjB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,QAAQ,CAAI,KAAQ;IAChC,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC;AACvB,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,IAAI;IAChB,uBAAuB;AAC3B,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,IAAI,CAAwB,EAAK;IAC7C,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,MAAqB,CAAC;IAE1B,OAAO,UAAsC,GAAG,IAAmB;QAC/D,IAAI,CAAC,MAAM,EAAE,CAAC;YACV,MAAM,GAAG,IAAI,CAAC;YACd,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAClC,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAM,CAAC;AACX,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,OAAO,CACnB,EAAK,EACL,QAAwC,EACxC,QAA+B,IAAI,GAAG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tC,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC;AAC3B,CAAC;AAoBD,MAAM,UAAU,OAAO,CAAC,GAAG,GAAkB;IACzC,OAAO,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;AAC7C,CAAC;AAED,SAAS,UAAU,CAAC,GAAkB;IAClC,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,QAAQ,CAAC;IAEtC,OAAO,UAAqB,GAAG,IAAW;QACtC,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAClC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACvC,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAC,CAAC;AACN,CAAC;AAED,SAAS,cAAc,CAAC,IAAY;IAChC,OAAO,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACzD,CAAC","sourcesContent":["type AnyFunction = (this: any, ...args: any[]) => any;\ntype TimerHandle = ReturnType<typeof setTimeout>;\n\n/** Options that control when a debounced function is executed. */\nexport interface DebounceOptions {\n /** Execute on the first call in a debounce window. Defaults to false. */\n leading?: boolean;\n /** Execute after the debounce window using the latest arguments. Defaults to true. */\n trailing?: boolean;\n}\n\n/** Options that control when a throttled function is executed. */\nexport interface ThrottleOptions {\n /** Execute immediately on the first call in a throttle window. Defaults to true. */\n leading?: boolean;\n /** Execute once more at the end of the throttle window using the latest arguments. Defaults to true. */\n trailing?: boolean;\n}\n\n/**\n * A delayed function returned by {@link debounce} or {@link throttle}.\n *\n * @example\n * ```ts\n * const saveLater = debounce(save, 250);\n * saveLater();\n *\n * if (saveLater.pending()) {\n * saveLater.flush();\n * }\n * ```\n */\nexport type DeferredFunction<F extends AnyFunction> = ((\n this: ThisParameterType<F>,\n ...args: Parameters<F>\n) => ReturnType<F> | undefined) & {\n /** Cancel the scheduled call and forget the latest arguments. */\n cancel(): void;\n /** Execute the scheduled trailing call immediately, when one exists. */\n flush(): ReturnType<F> | undefined;\n /** Return true while a trailing call is scheduled. */\n pending(): boolean;\n};\n\n/**\n * A memoized function with helpers for inspecting and invalidating its cache.\n *\n * @example\n * ```ts\n * const getUser = memoize((id: string) => fetchUser(id));\n *\n * getUser(\"42\");\n * getUser.has(\"42\"); // true\n * getUser.delete(\"42\");\n * ```\n */\nexport type MemoizedFunction<F extends AnyFunction, K> = ((\n this: ThisParameterType<F>,\n ...args: Parameters<F>\n) => ReturnType<F>) & {\n /** The backing cache used by the memoized function. */\n readonly cache: Map<K, ReturnType<F>>;\n /** Remove every cached value. */\n clear(): void;\n /** Remove the cached value for the key resolved from the provided arguments. */\n delete(...args: Parameters<F>): boolean;\n /** Return true when a cached value exists for the key resolved from the provided arguments. */\n has(...args: Parameters<F>): boolean;\n};\n\ntype Unary<T, R> = (arg: T) => R;\n\n/**\n * Return the received value unchanged.\n * Useful as a default mapper, placeholder callback, or neutral transform in a pipeline.\n *\n * @example\n * ```ts\n * identity(5); // 5\n *\n * const value = {name: \"commons\"};\n * identity(value) === value; // true\n * ```\n */\nexport function identity<T>(value: T): T {\n return value;\n}\n\n/**\n * Create a function that always returns the same value.\n *\n * @example\n * ```ts\n * const getAnswer = constant(42);\n *\n * getAnswer(); // 42\n * getAnswer(); // 42\n * ```\n */\nexport function constant<T>(value: T): () => T {\n return () => value;\n}\n\n/**\n * Do nothing and return undefined.\n * Useful as a safe default callback.\n *\n * @example\n * ```ts\n * const onComplete = options.onComplete ?? noop;\n * onComplete();\n * ```\n */\nexport function noop(): void {\n // Intentionally empty.\n}\n\n/**\n * Create a function that can be executed only once.\n * Later calls return the result from the first execution without calling the original function again.\n *\n * @example\n * ```ts\n * const initialize = once(() => ({connected: true}));\n *\n * const first = initialize();\n * const second = initialize();\n * first === second; // true\n * ```\n */\nexport function once<F extends AnyFunction>(fn: F): F {\n let called = false;\n let result: ReturnType<F>;\n\n return function (this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F> {\n if (!called) {\n called = true;\n result = fn.apply(this, args);\n }\n return result;\n } as F;\n}\n\n/**\n * Cache the result of a function and reuse it for calls with the same resolved key.\n * By default, the first argument is used as the cache key.\n *\n * @example\n * ```ts\n * const double = memoize((value: number) => value * 2);\n *\n * double(4); // 8, computed\n * double(4); // 8, read from cache\n * double.has(4); // true\n * ```\n *\n * @example\n * ```ts\n * const sum = memoize(\n * (left: number, right: number) => left + right,\n * (left, right) => `${left}:${right}`,\n * );\n *\n * sum(2, 3); // 5\n * sum.delete(2, 3); // true\n * sum.clear();\n * ```\n */\nexport function memoize<F extends AnyFunction, K = Parameters<F>[0]>(\n fn: F,\n resolver?: (...args: Parameters<F>) => K,\n cache: Map<K, ReturnType<F>> = new Map<K, ReturnType<F>>()\n): MemoizedFunction<F, K> {\n const resolveKey = (...args: Parameters<F>): K => {\n if (resolver) return resolver(...args);\n return args[0] as K;\n };\n\n const memoized = function (this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F> {\n const key = resolveKey(...args);\n if (cache.has(key)) {\n return cache.get(key)!;\n }\n\n const value = fn.apply(this, args);\n cache.set(key, value);\n return value;\n } as MemoizedFunction<F, K>;\n\n Object.defineProperty(memoized, \"cache\", {\n value: cache,\n enumerable: false,\n });\n\n memoized.clear = () => cache.clear();\n memoized.delete = (...args: Parameters<F>) => cache.delete(resolveKey(...args));\n memoized.has = (...args: Parameters<F>) => cache.has(resolveKey(...args));\n\n return memoized;\n}\n\n/**\n * Delay a function until no calls have been made for the configured wait time.\n * The latest arguments and this-context are used for the trailing execution.\n *\n * @example\n * ```ts\n * const search = debounce((query: string) => {\n * console.log(query);\n * }, 300);\n *\n * search(\"com\");\n * search(\"commons\"); // only this value is printed after 300 ms\n * ```\n *\n * @example\n * ```ts\n * const track = debounce(sendAnalytics, 1000, {leading: true, trailing: false});\n *\n * track(\"open\"); // executed immediately\n * track.cancel(); // cancel the pending debounce window\n * ```\n */\nexport function debounce<F extends AnyFunction>(\n fn: F,\n wait: number,\n options: DebounceOptions = {}\n): DeferredFunction<F> {\n const delay = normalizeDelay(wait);\n const leading = options.leading ?? false;\n const trailing = options.trailing ?? true;\n\n let timer: TimerHandle | undefined;\n let lastArgs: Parameters<F> | undefined;\n let lastThis: ThisParameterType<F> | undefined;\n let result: ReturnType<F> | undefined;\n\n const invoke = (): ReturnType<F> => {\n const args = lastArgs!;\n const context = lastThis!;\n lastArgs = undefined;\n lastThis = undefined;\n result = fn.apply(context, args);\n return result as ReturnType<F>;\n };\n\n const expire = (): void => {\n timer = undefined;\n if (trailing && lastArgs) {\n invoke();\n } else {\n lastArgs = undefined;\n lastThis = undefined;\n }\n };\n\n const start = (): void => {\n timer = setTimeout(expire, delay);\n };\n\n const debounced = function (this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F> | undefined {\n const invokeLeading = leading && timer === undefined;\n lastArgs = args;\n lastThis = this;\n\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n start();\n\n if (invokeLeading) {\n return invoke();\n }\n\n return result;\n } as DeferredFunction<F>;\n\n debounced.cancel = (): void => {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n timer = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n };\n\n debounced.flush = (): ReturnType<F> | undefined => {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n if (lastArgs && trailing) {\n return invoke();\n }\n }\n return result;\n };\n\n debounced.pending = (): boolean => timer !== undefined;\n\n return debounced;\n}\n\n/**\n * Limit how often a function can run during a time window.\n * Calls made while the function is throttled can optionally be replayed once at the end with the latest arguments.\n *\n * @example\n * ```ts\n * const onScroll = throttle(() => {\n * console.log(window.scrollY);\n * }, 100);\n *\n * window.addEventListener(\"scroll\", onScroll);\n * ```\n *\n * @example\n * ```ts\n * const refresh = throttle(loadData, 500, {leading: false});\n *\n * refresh(); // scheduled instead of executed immediately\n * refresh.flush(); // execute the scheduled call now\n * ```\n */\nexport function throttle<F extends AnyFunction>(\n fn: F,\n wait: number,\n options: ThrottleOptions = {}\n): DeferredFunction<F> {\n const delay = normalizeDelay(wait);\n const leading = options.leading ?? true;\n const trailing = options.trailing ?? true;\n\n let timer: TimerHandle | undefined;\n let lastArgs: Parameters<F> | undefined;\n let lastThis: ThisParameterType<F> | undefined;\n let lastInvokeTime = 0;\n let hasInvoked = false;\n let result: ReturnType<F> | undefined;\n\n const invoke = (time: number): ReturnType<F> => {\n const args = lastArgs!;\n const context = lastThis!;\n lastArgs = undefined;\n lastThis = undefined;\n hasInvoked = true;\n lastInvokeTime = time;\n result = fn.apply(context, args);\n return result as ReturnType<F>;\n };\n\n const expire = (): void => {\n timer = undefined;\n if (trailing && lastArgs) {\n invoke(Date.now());\n } else {\n lastArgs = undefined;\n lastThis = undefined;\n }\n };\n\n const throttled = function (this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F> | undefined {\n const now = Date.now();\n lastArgs = args;\n lastThis = this;\n\n if (!hasInvoked) {\n if (leading) {\n return invoke(now);\n }\n hasInvoked = true;\n lastInvokeTime = now;\n }\n\n const remaining = delay - (now - lastInvokeTime);\n if (remaining <= 0 || remaining > delay) {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n return invoke(now);\n }\n\n if (timer === undefined && trailing) {\n timer = setTimeout(expire, remaining);\n }\n\n return result;\n } as DeferredFunction<F>;\n\n throttled.cancel = (): void => {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n timer = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n lastInvokeTime = 0;\n hasInvoked = false;\n };\n\n throttled.flush = (): ReturnType<F> | undefined => {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n if (lastArgs && trailing) {\n return invoke(Date.now());\n }\n }\n return result;\n };\n\n throttled.pending = (): boolean => timer !== undefined;\n\n return throttled;\n}\n\n/**\n * Create a function with one or more arguments already provided.\n * Later arguments are appended after the preset arguments.\n *\n * @example\n * ```ts\n * const sum = (a: number, b: number, c: number) => a + b + c;\n * const addFive = partial(sum, 2, 3);\n *\n * addFive(4); // 9\n * ```\n */\nexport function partial<F extends AnyFunction>(\n fn: F,\n ...presetArgs: unknown[]\n): (...laterArgs: unknown[]) => ReturnType<F> {\n return function (this: ThisParameterType<F>, ...laterArgs: unknown[]): ReturnType<F> {\n return fn.apply(this, [...presetArgs, ...laterArgs] as Parameters<F>);\n };\n}\n\n/**\n * Compose unary functions from left to right.\n * The first function receives the original arguments, and each next function receives the previous result.\n *\n * @example\n * ```ts\n * const transform = pipe(\n * (value: number) => value + 1,\n * (value: number) => value * 2,\n * );\n *\n * transform(2); // 6\n * ```\n */\nexport function pipe<A, B>(ab: Unary<A, B>): Unary<A, B>;\nexport function pipe<A, B, C>(ab: Unary<A, B>, bc: Unary<B, C>): Unary<A, C>;\nexport function pipe<A, B, C, D>(ab: Unary<A, B>, bc: Unary<B, C>, cd: Unary<C, D>): Unary<A, D>;\nexport function pipe<A, B, C, D, E>(ab: Unary<A, B>, bc: Unary<B, C>, cd: Unary<C, D>, de: Unary<D, E>): Unary<A, E>;\nexport function pipe(...fns: AnyFunction[]): AnyFunction {\n return createFlow(fns);\n}\n\n/**\n * Compose unary functions from right to left.\n * The rightmost function receives the original arguments, and each function to its left receives the previous result.\n *\n * @example\n * ```ts\n * const transform = compose(\n * (value: number) => value + 1,\n * (value: number) => value * 2,\n * );\n *\n * transform(2); // 5\n * ```\n */\nexport function compose<A, B>(ab: Unary<A, B>): Unary<A, B>;\nexport function compose<A, B, C>(bc: Unary<B, C>, ab: Unary<A, B>): Unary<A, C>;\nexport function compose<A, B, C, D>(cd: Unary<C, D>, bc: Unary<B, C>, ab: Unary<A, B>): Unary<A, D>;\nexport function compose<A, B, C, D, E>(de: Unary<D, E>, cd: Unary<C, D>, bc: Unary<B, C>, ab: Unary<A, B>): Unary<A, E>;\nexport function compose(...fns: AnyFunction[]): AnyFunction {\n return createFlow(fns.slice().reverse());\n}\n\nfunction createFlow(fns: AnyFunction[]): AnyFunction {\n if (fns.length === 0) return identity;\n\n return function (this: any, ...args: any[]): unknown {\n let result = fns[0].apply(this, args);\n for (let i = 1; i < fns.length; i++) {\n result = fns[i].call(this, result);\n }\n return result;\n };\n}\n\nfunction normalizeDelay(wait: number): number {\n return Number.isFinite(wait) ? Math.max(0, wait) : 0;\n}"]}
1
+ {"version":3,"file":"functions.js","sourceRoot":"","sources":["../../src/functions.ts"],"names":[],"mappings":"AAgEA;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,QAAQ,CAAI,KAAQ;IAChC,OAAO,KAAK,CAAC;AACjB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,QAAQ,CAAI,KAAQ;IAChC,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC;AACvB,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,IAAI;IAChB,uBAAuB;AAC3B,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,IAAI,CAAwB,EAAK;IAC7C,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,MAAqB,CAAC;IAE1B,OAAO,UAAsC,GAAG,IAAmB;QAC/D,IAAI,CAAC,MAAM,EAAE,CAAC;YACV,MAAM,GAAG,IAAI,CAAC;YACd,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAClC,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAM,CAAC;AACX,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,OAAO,CACnB,EAAK,EACL,QAAwC,EACxC,QAA+B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AC,CAAC;AACzD,CAAC","sourcesContent":["type AnyFunction = (this: any, ...args: any[]) => any;\ntype TimerHandle = ReturnType<typeof setTimeout>;\n\n/** Options that control when a throttled function is executed. */\nexport interface ThrottleOptions {\n /** Execute immediately on the first call in a throttle window. Defaults to true. */\n leading?: boolean;\n /** Execute once more at the end of the throttle window using the latest arguments. Defaults to true. */\n trailing?: boolean;\n}\n\n/**\n * A delayed function returned by {@link throttle}.\n *\n * @example\n * ```ts\n * const refresh = throttle(loadData, 250);\n * refresh();\n *\n * if (refresh.pending()) {\n * refresh.flush();\n * }\n * ```\n */\nexport type DeferredFunction<F extends AnyFunction> = ((\n this: ThisParameterType<F>,\n ...args: Parameters<F>\n) => ReturnType<F> | undefined) & {\n /** Cancel the scheduled call and forget the latest arguments. */\n cancel(): void;\n /** Execute the scheduled trailing call immediately, when one exists. */\n flush(): ReturnType<F> | undefined;\n /** Return true while a trailing call is scheduled. */\n pending(): boolean;\n};\n\n/**\n * A memoized function with helpers for inspecting and invalidating its cache.\n *\n * @example\n * ```ts\n * const getUser = memoize((id: string) => fetchUser(id));\n *\n * getUser(\"42\");\n * getUser.has(\"42\"); // true\n * getUser.delete(\"42\");\n * ```\n */\nexport type MemoizedFunction<F extends AnyFunction, K> = ((\n this: ThisParameterType<F>,\n ...args: Parameters<F>\n) => ReturnType<F>) & {\n /** The backing cache used by the memoized function. */\n readonly cache: Map<K, ReturnType<F>>;\n /** Remove every cached value. */\n clear(): void;\n /** Remove the cached value for the key resolved from the provided arguments. */\n delete(...args: Parameters<F>): boolean;\n /** Return true when a cached value exists for the key resolved from the provided arguments. */\n has(...args: Parameters<F>): boolean;\n};\n\ntype Unary<T, R> = (arg: T) => R;\n\n/**\n * Return the received value unchanged.\n * Useful as a default mapper, placeholder callback, or neutral transform in a pipeline.\n *\n * @example\n * ```ts\n * identity(5); // 5\n *\n * const value = {name: \"commons\"};\n * identity(value) === value; // true\n * ```\n */\nexport function identity<T>(value: T): T {\n return value;\n}\n\n/**\n * Create a function that always returns the same value.\n *\n * @example\n * ```ts\n * const getAnswer = constant(42);\n *\n * getAnswer(); // 42\n * getAnswer(); // 42\n * ```\n */\nexport function constant<T>(value: T): () => T {\n return () => value;\n}\n\n/**\n * Do nothing and return undefined.\n * Useful as a safe default callback.\n *\n * @example\n * ```ts\n * const onComplete = options.onComplete ?? noop;\n * onComplete();\n * ```\n */\nexport function noop(): void {\n // Intentionally empty.\n}\n\n/**\n * Create a function that can be executed only once.\n * Later calls return the result from the first execution without calling the original function again.\n *\n * @example\n * ```ts\n * const initialize = once(() => ({connected: true}));\n *\n * const first = initialize();\n * const second = initialize();\n * first === second; // true\n * ```\n */\nexport function once<F extends AnyFunction>(fn: F): F {\n let called = false;\n let result: ReturnType<F>;\n\n return function (this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F> {\n if (!called) {\n called = true;\n result = fn.apply(this, args);\n }\n return result;\n } as F;\n}\n\n/**\n * Cache the result of a function and reuse it for calls with the same resolved key.\n * By default, the first argument is used as the cache key.\n *\n * @example\n * ```ts\n * const double = memoize((value: number) => value * 2);\n *\n * double(4); // 8, computed\n * double(4); // 8, read from cache\n * double.has(4); // true\n * ```\n *\n * @example\n * ```ts\n * const sum = memoize(\n * (left: number, right: number) => left + right,\n * (left, right) => `${left}:${right}`,\n * );\n *\n * sum(2, 3); // 5\n * sum.delete(2, 3); // true\n * sum.clear();\n * ```\n */\nexport function memoize<F extends AnyFunction, K = Parameters<F>[0]>(\n fn: F,\n resolver?: (...args: Parameters<F>) => K,\n cache: Map<K, ReturnType<F>> = new Map<K, ReturnType<F>>()\n): MemoizedFunction<F, K> {\n const resolveKey = (...args: Parameters<F>): K => {\n if (resolver) return resolver(...args);\n return args[0] as K;\n };\n\n const memoized = function (this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F> {\n const key = resolveKey(...args);\n if (cache.has(key)) {\n return cache.get(key)!;\n }\n\n const value = fn.apply(this, args);\n cache.set(key, value);\n return value;\n } as MemoizedFunction<F, K>;\n\n Object.defineProperty(memoized, \"cache\", {\n value: cache,\n enumerable: false,\n });\n\n memoized.clear = () => cache.clear();\n memoized.delete = (...args: Parameters<F>) => cache.delete(resolveKey(...args));\n memoized.has = (...args: Parameters<F>) => cache.has(resolveKey(...args));\n\n return memoized;\n}\n\n/**\n * Limit how often a function can run during a time window.\n * Calls made while the function is throttled can optionally be replayed once at the end with the latest arguments.\n *\n * @example\n * ```ts\n * const onScroll = throttle(() => {\n * console.log(window.scrollY);\n * }, 100);\n *\n * window.addEventListener(\"scroll\", onScroll);\n * ```\n *\n * @example\n * ```ts\n * const refresh = throttle(loadData, 500, {leading: false});\n *\n * refresh(); // scheduled instead of executed immediately\n * refresh.flush(); // execute the scheduled call now\n * ```\n */\nexport function throttle<F extends AnyFunction>(\n fn: F,\n wait: number,\n options: ThrottleOptions = {}\n): DeferredFunction<F> {\n const delay = normalizeDelay(wait);\n const leading = options.leading ?? true;\n const trailing = options.trailing ?? true;\n\n let timer: TimerHandle | undefined;\n let lastArgs: Parameters<F> | undefined;\n let lastThis: ThisParameterType<F> | undefined;\n let lastInvokeTime = 0;\n let hasInvoked = false;\n let result: ReturnType<F> | undefined;\n\n const invoke = (time: number): ReturnType<F> => {\n const args = lastArgs!;\n const context = lastThis!;\n lastArgs = undefined;\n lastThis = undefined;\n hasInvoked = true;\n lastInvokeTime = time;\n result = fn.apply(context, args);\n return result as ReturnType<F>;\n };\n\n const expire = (): void => {\n timer = undefined;\n if (trailing && lastArgs) {\n invoke(Date.now());\n } else {\n lastArgs = undefined;\n lastThis = undefined;\n }\n };\n\n const throttled = function (this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F> | undefined {\n const now = Date.now();\n lastArgs = args;\n lastThis = this;\n\n if (!hasInvoked) {\n if (leading) {\n return invoke(now);\n }\n hasInvoked = true;\n lastInvokeTime = now;\n }\n\n const remaining = delay - (now - lastInvokeTime);\n if (remaining <= 0 || remaining > delay) {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n return invoke(now);\n }\n\n if (timer === undefined && trailing) {\n timer = setTimeout(expire, remaining);\n }\n\n return result;\n } as DeferredFunction<F>;\n\n throttled.cancel = (): void => {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n timer = undefined;\n lastArgs = undefined;\n lastThis = undefined;\n lastInvokeTime = 0;\n hasInvoked = false;\n };\n\n throttled.flush = (): ReturnType<F> | undefined => {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n if (lastArgs && trailing) {\n return invoke(Date.now());\n }\n }\n return result;\n };\n\n throttled.pending = (): boolean => timer !== undefined;\n\n return throttled;\n}\n\n/**\n * Create a function with one or more arguments already provided.\n * Later arguments are appended after the preset arguments.\n *\n * @example\n * ```ts\n * const sum = (a: number, b: number, c: number) => a + b + c;\n * const addFive = partial(sum, 2, 3);\n *\n * addFive(4); // 9\n * ```\n */\nexport function partial<F extends AnyFunction>(\n fn: F,\n ...presetArgs: unknown[]\n): (...laterArgs: unknown[]) => ReturnType<F> {\n return function (this: ThisParameterType<F>, ...laterArgs: unknown[]): ReturnType<F> {\n return fn.apply(this, [...presetArgs, ...laterArgs] as Parameters<F>);\n };\n}\n\n/**\n * Compose unary functions from left to right.\n * The first function receives the original arguments, and each next function receives the previous result.\n *\n * @example\n * ```ts\n * const transform = pipe(\n * (value: number) => value + 1,\n * (value: number) => value * 2,\n * );\n *\n * transform(2); // 6\n * ```\n */\nexport function pipe<A, B>(ab: Unary<A, B>): Unary<A, B>;\nexport function pipe<A, B, C>(ab: Unary<A, B>, bc: Unary<B, C>): Unary<A, C>;\nexport function pipe<A, B, C, D>(ab: Unary<A, B>, bc: Unary<B, C>, cd: Unary<C, D>): Unary<A, D>;\nexport function pipe<A, B, C, D, E>(ab: Unary<A, B>, bc: Unary<B, C>, cd: Unary<C, D>, de: Unary<D, E>): Unary<A, E>;\nexport function pipe(...fns: AnyFunction[]): AnyFunction {\n return createFlow(fns);\n}\n\n/**\n * Compose unary functions from right to left.\n * The rightmost function receives the original arguments, and each function to its left receives the previous result.\n *\n * @example\n * ```ts\n * const transform = compose(\n * (value: number) => value + 1,\n * (value: number) => value * 2,\n * );\n *\n * transform(2); // 5\n * ```\n */\nexport function compose<A, B>(ab: Unary<A, B>): Unary<A, B>;\nexport function compose<A, B, C>(bc: Unary<B, C>, ab: Unary<A, B>): Unary<A, C>;\nexport function compose<A, B, C, D>(cd: Unary<C, D>, bc: Unary<B, C>, ab: Unary<A, B>): Unary<A, D>;\nexport function compose<A, B, C, D, E>(de: Unary<D, E>, cd: Unary<C, D>, bc: Unary<B, C>, ab: Unary<A, B>): Unary<A, E>;\nexport function compose(...fns: AnyFunction[]): AnyFunction {\n return createFlow(fns.slice().reverse());\n}\n\nfunction createFlow(fns: AnyFunction[]): AnyFunction {\n if (fns.length === 0) return identity;\n\n return function (this: any, ...args: any[]): unknown {\n let result = fns[0].apply(this, args);\n for (let i = 1; i < fns.length; i++) {\n result = fns[i].call(this, result);\n }\n return result;\n };\n}\n\nfunction normalizeDelay(wait: number): number {\n return Number.isFinite(wait) ? Math.max(0, wait) : 0;\n}"]}
package/dist/web/index.js CHANGED
@@ -19,6 +19,8 @@ export { default as TimeSpan } from './timespan.js';
19
19
  export { default as Stopwatch } from './stopwatch.js';
20
20
  export { TimeTrigger, CountTrigger } from './triggers.js';
21
21
  export { default as AsyncPoolExecutor } from './async-pool-executor.js';
22
+ export { default as Debouncer } from './debouncer.js';
23
+ export { default as KeyedDebouncer } from './keyed-debouncer.js';
22
24
  // ─── Patterns ────────────────────────────────────────
23
25
  export { default as Lazy } from './lazy.js';
24
26
  export { default as from } from './collections/from.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,eAAe;AAEf,wDAAwD;AACxD,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAC,OAAO,IAAI,IAAI,EAAC,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAC,OAAO,IAAI,QAAQ,EAA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wDAAwD;AACxD,mBAAmB;AACnB,cAAc,YAAY,CAAC;AAC3B,mBAAmB;AACnB,cAAc,wBAAwB,CAAC","sourcesContent":["// src/index.ts\n\n// ─── Types ───────────────────────────────────────────\nexport * from './types.js';\nexport {default as Type} from './type.js';\nexport {default as TypeCode} from './type-code.js';\n\n// ─── Utilities ───────────────────────────────────────\nexport * from './utilities.js';\nexport * from './functions.js';\nexport * from './string.js';\nexport * from './math.js';\nexport * from './parse.js';\nexport {default as CancellablePromise} from \"./cancellable-promise.js\";\n\n// ─── Data Structures ────────────────────────────────\nexport {default as KeyValuePair} from './key-value-pair.js';\nexport {default as Order} from './order.js';\n\n// ─── Async & Timing ─────────────────────────────────\nexport {default as Timer} from './timer.js';\nexport {default as TimeSpan} from './timespan.js';\nexport {default as Stopwatch} from './stopwatch.js';\nexport type {Result} from './result.js';\nexport {TimeTrigger, CountTrigger} from './triggers.js';\nexport {default as AsyncPoolExecutor} from './async-pool-executor.js';\n\n// ─── Patterns ────────────────────────────────────────\nexport {default as Lazy} from './lazy.js';\nexport {default as from} from './collections/from.js';\nexport {EventBus, Event} from './event-bus.js';\nexport {default as Range} from './range.js';\n\n// ─── Draft ────────────────────────────────────────\nexport {default as draft} from './draft.js';\n\n// ─── Web ─────────────────────────────────────────────\nexport {default as CleanURLSearchParams} from './clean-url-search-params.js';\n/** @deprecated */\nexport {ajaxSubmit, ajaxSubmission, submitForm, formToObject} from './browser/index.js';\n\n\n\n// ─── Deprecated ──────────────────────────────────────\n/** @deprecated */\nexport * from './array.js';\n/** @deprecated */\nexport * from './collections/index.js';"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,eAAe;AAEf,wDAAwD;AACxD,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAC,OAAO,IAAI,IAAI,EAAC,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAC,OAAO,IAAI,QAAQ,EAAC,MAAM,gBAAgB,CAAC;AAEnD,w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;AACnB,OAAO,EAAC,UAAU,EAAE,cAAc,EAAE,UAAU,EAAE,YAAY,EAAC,MAAM,oBAAoB,CAAC;AAIxF,wDAAwD;AACxD,mBAAmB;AACnB,cAAc,YAAY,CAAC;AAC3B,mBAAmB;AACnB,cAAc,wBAAwB,CAAC","sourcesContent":["// src/index.ts\n\n// ─── Types ───────────────────────────────────────────\nexport * from './types.js';\nexport {default as Type} from './type.js';\nexport {default as TypeCode} from './type-code.js';\n\n// ─── Utilities ───────────────────────────────────────\nexport * from './utilities.js';\nexport * from './functions.js';\nexport * from './string.js';\nexport * from './math.js';\nexport * from './parse.js';\nexport {default as CancellablePromise} from \"./cancellable-promise.js\";\n\n// ─── Data Structures ────────────────────────────────\nexport {default as KeyValuePair} from './key-value-pair.js';\nexport {default as Order} from './order.js';\n\n// ─── Async & Timing ─────────────────────────────────\nexport {default as Timer} from './timer.js';\nexport {default as TimeSpan} from './timespan.js';\nexport {default as Stopwatch} from './stopwatch.js';\nexport type {Result} from './result.js';\nexport {TimeTrigger, CountTrigger} from './triggers.js';\nexport {default as AsyncPoolExecutor} from './async-pool-executor.js';\nexport {default as Debouncer} from './debouncer.js';\nexport type {DebouncedTask, DebouncerOptions} from './debouncer.js';\nexport {default as KeyedDebouncer} from './keyed-debouncer.js';\nexport type {KeyedDebouncerOptions} from './keyed-debouncer.js';\n\n// ─── Patterns ────────────────────────────────────────\nexport {default as Lazy} from './lazy.js';\nexport {default as from} from './collections/from.js';\nexport {EventBus, Event} from './event-bus.js';\nexport {default as Range} from './range.js';\n\n// ─── Draft ────────────────────────────────────────\nexport {default as draft} from './draft.js';\n\n// ─── Web ─────────────────────────────────────────────\nexport {default as CleanURLSearchParams} from './clean-url-search-params.js';\n/** @deprecated */\nexport {ajaxSubmit, ajaxSubmission, submitForm, formToObject} from './browser/index.js';\n\n\n\n// ─── Deprecated ──────────────────────────────────────\n/** @deprecated */\nexport * from './array.js';\n/** @deprecated */\nexport * from './collections/index.js';"]}
@@ -0,0 +1,109 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _KeyedDebouncer_instances, _KeyedDebouncer_debouncers, _KeyedDebouncer_delayMs, _KeyedDebouncer_onSchedule, _KeyedDebouncer_onStart, _KeyedDebouncer_onSuccess, _KeyedDebouncer_onCancel, _KeyedDebouncer_onError, _KeyedDebouncer_onIdle, _KeyedDebouncer_create;
13
+ import Debouncer, { assertValidDelay } from "./debouncer.js";
14
+ import { noop } from "./functions.js";
15
+ /**
16
+ * An independent {@link Debouncer} per key.
17
+ * Debouncers only exist for keys with pending work: each one is created when
18
+ * its first task is scheduled and removed as soon as it becomes idle.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const debouncer = new KeyedDebouncer<string>({delayMs: 1500});
23
+ *
24
+ * debouncer.schedule(chatId, async (signal) => {
25
+ * const pending = await store.getPending(chatId);
26
+ * const reply = await callAI(pending, {signal});
27
+ * if (signal.aborted) return;
28
+ * await sendReply(chatId, reply);
29
+ * });
30
+ * ```
31
+ */
32
+ class KeyedDebouncer {
33
+ constructor(options) {
34
+ _KeyedDebouncer_instances.add(this);
35
+ _KeyedDebouncer_debouncers.set(this, new Map());
36
+ _KeyedDebouncer_delayMs.set(this, void 0);
37
+ _KeyedDebouncer_onSchedule.set(this, void 0);
38
+ _KeyedDebouncer_onStart.set(this, void 0);
39
+ _KeyedDebouncer_onSuccess.set(this, void 0);
40
+ _KeyedDebouncer_onCancel.set(this, void 0);
41
+ _KeyedDebouncer_onError.set(this, void 0);
42
+ _KeyedDebouncer_onIdle.set(this, void 0);
43
+ assertValidDelay(options.delayMs);
44
+ __classPrivateFieldSet(this, _KeyedDebouncer_delayMs, options.delayMs, "f");
45
+ __classPrivateFieldSet(this, _KeyedDebouncer_onSchedule, options.onSchedule ?? noop, "f");
46
+ __classPrivateFieldSet(this, _KeyedDebouncer_onStart, options.onStart ?? noop, "f");
47
+ __classPrivateFieldSet(this, _KeyedDebouncer_onSuccess, options.onSuccess ?? noop, "f");
48
+ __classPrivateFieldSet(this, _KeyedDebouncer_onCancel, options.onCancel ?? noop, "f");
49
+ __classPrivateFieldSet(this, _KeyedDebouncer_onError, options.onError ?? console.error, "f");
50
+ __classPrivateFieldSet(this, _KeyedDebouncer_onIdle, options.onIdle ?? noop, "f");
51
+ }
52
+ /** Number of keys with a task waiting or running. */
53
+ get size() {
54
+ return __classPrivateFieldGet(this, _KeyedDebouncer_debouncers, "f").size;
55
+ }
56
+ /**
57
+ * Schedule `task` for `key`, cancelling any previous task of that key.
58
+ *
59
+ * @param key - The key whose task is replaced.
60
+ * @param task - The task to run once the delay elapses.
61
+ * @param delayMs - Wait for this task only. Defaults to the configured `delayMs`.
62
+ */
63
+ schedule(key, task, delayMs) {
64
+ const existing = __classPrivateFieldGet(this, _KeyedDebouncer_debouncers, "f").get(key);
65
+ if (existing !== undefined) {
66
+ existing.schedule(task, delayMs);
67
+ return;
68
+ }
69
+ // Validate first so an invalid delay never registers the key.
70
+ assertValidDelay(delayMs ?? __classPrivateFieldGet(this, _KeyedDebouncer_delayMs, "f"));
71
+ const debouncer = __classPrivateFieldGet(this, _KeyedDebouncer_instances, "m", _KeyedDebouncer_create).call(this, key);
72
+ __classPrivateFieldGet(this, _KeyedDebouncer_debouncers, "f").set(key, debouncer);
73
+ debouncer.schedule(task, delayMs);
74
+ }
75
+ /** Cancel the task of `key`, if any. */
76
+ cancel(key) {
77
+ __classPrivateFieldGet(this, _KeyedDebouncer_debouncers, "f").get(key)?.cancel();
78
+ }
79
+ /** Cancel every task. Useful when shutting the process down. */
80
+ cancelAll() {
81
+ // Copy first: cancelling removes the debouncer from the map.
82
+ for (const debouncer of [...__classPrivateFieldGet(this, _KeyedDebouncer_debouncers, "f").values()]) {
83
+ debouncer.cancel();
84
+ }
85
+ }
86
+ /** Whether a task is waiting or running for `key`. */
87
+ isPending(key) {
88
+ return __classPrivateFieldGet(this, _KeyedDebouncer_debouncers, "f").has(key);
89
+ }
90
+ }
91
+ _KeyedDebouncer_debouncers = new WeakMap(), _KeyedDebouncer_delayMs = new WeakMap(), _KeyedDebouncer_onSchedule = new WeakMap(), _KeyedDebouncer_onStart = new WeakMap(), _KeyedDebouncer_onSuccess = new WeakMap(), _KeyedDebouncer_onCancel = new WeakMap(), _KeyedDebouncer_onError = new WeakMap(), _KeyedDebouncer_onIdle = new WeakMap(), _KeyedDebouncer_instances = new WeakSet(), _KeyedDebouncer_create = function _KeyedDebouncer_create(key) {
92
+ const debouncer = new Debouncer({
93
+ delayMs: __classPrivateFieldGet(this, _KeyedDebouncer_delayMs, "f"),
94
+ onSchedule: () => __classPrivateFieldGet(this, _KeyedDebouncer_onSchedule, "f").call(this, key),
95
+ onStart: () => __classPrivateFieldGet(this, _KeyedDebouncer_onStart, "f").call(this, key),
96
+ onSuccess: () => __classPrivateFieldGet(this, _KeyedDebouncer_onSuccess, "f").call(this, key),
97
+ onCancel: () => __classPrivateFieldGet(this, _KeyedDebouncer_onCancel, "f").call(this, key),
98
+ onError: (error) => __classPrivateFieldGet(this, _KeyedDebouncer_onError, "f").call(this, error, key),
99
+ onIdle: () => {
100
+ if (__classPrivateFieldGet(this, _KeyedDebouncer_debouncers, "f").get(key) === debouncer) {
101
+ __classPrivateFieldGet(this, _KeyedDebouncer_debouncers, "f").delete(key);
102
+ __classPrivateFieldGet(this, _KeyedDebouncer_onIdle, "f").call(this, key);
103
+ }
104
+ },
105
+ });
106
+ return debouncer;
107
+ };
108
+ export default KeyedDebouncer;
109
+ //# sourceMappingURL=keyed-debouncer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyed-debouncer.js","sourceRoot":"","sources":["../../src/keyed-debouncer.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,SAAS,EAAE,EAAC,gBAAgB,EAAqB,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAC,IAAI,EAAC,MAAM,gBAAgB,CAAC;AAoBpC;;;;;;;;;;;;;;;;GAgBG;AACH,MAAqB,cAAc;IAU/B,YAAY,OAAiC;;QATpC,qCAAc,IAAI,GAAG,EAAgB,EAAC;QACtC,0CAAiB;QACjB,6CAA8B;QAC9B,0CAA2B;QAC3B,4CAA6B;QAC7B,2CAA4B;QAC5B,0CAA2C;QAC3C,yCAA0B;QAG/B,gBAAgB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAClC,uBAAA,IAAI,2BAAY,OAAO,CAAC,OAAO,MAAA,CAAC;QAChC,uBAAA,IAAI,8BAAe,OAAO,CAAC,UAAU,IAAI,IAAI,MAAA,CAAC;QAC9C,uBAAA,IAAI,2BAAY,OAAO,CAAC,OAAO,IAAI,IAAI,MAAA,CAAC;QACxC,uBAAA,IAAI,6BAAc,OAAO,CAAC,SAAS,IAAI,IAAI,MAAA,CAAC;QAC5C,uBAAA,IAAI,4BAAa,OAAO,CAAC,QAAQ,IAAI,IAAI,MAAA,CAAC;QAC1C,uBAAA,IAAI,2BAAY,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC,KAAK,MAAA,CAAC;QACjD,uBAAA,IAAI,0BAAW,OAAO,CAAC,MAAM,IAAI,IAAI,MAAA,CAAC;IAC1C,CAAC;IAED,qDAAqD;IACrD,IAAI,IAAI;QACJ,OAAO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AAI,kCAAY,MAAhB,IAAI,EAAa,GAAG,CAAC;QACvC,OAAO,EAAE,GAAG,EAAE,CAAC,uBAAA,IAAI,+BAAS,MAAb,IAAI,EAAU,GAAG,CAAC;QACjC,SAAS,EAAE,GAAG,EAAE,CAAC,uBAAA,IAAI,iCAAW,MAAf,IAAI,EAAY,GAAG,CAAC;QACrC,QAAQ,EAAE,GAAG,EAAE,CAAC,uBAAA,IAAI,gCAAU,MAAd,IAAI,EAAW,GAAG,CAAC;QACnC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,uBAAA,IAAI,+BAAS,MAAb,IAAI,EAAU,KAAK,EAAE,GAAG,CAAC;QAC7C,MAAM,EAAE,GAAG,EAAE;YACT,IAAI,uBAAA,IAAI,kCAAY,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,SAAS,EAAE,CAAC;gBAC1C,uBAAA,IAAI,kCAAY,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC7B,uBAAA,IAAI,8BAAQ,MAAZ,IAAI,EAAS,GAAG,CAAC,CAAC;YACtB,CAAC;QACL,CAAC;KACJ,CAAC,CAAC;IACH,OAAO,SAAS,CAAC;AACrB,CAAC;eAjFgB,cAAc","sourcesContent":["import Debouncer, {assertValidDelay, type DebouncedTask} from \"./debouncer.js\";\nimport {noop} from \"./functions.js\";\n\n/** Options accepted by {@link KeyedDebouncer}. Every callback receives the affected key. */\nexport interface KeyedDebouncerOptions<K> {\n /** Default wait, in milliseconds, before a task is executed. */\n delayMs: number;\n /** Called every time a task is scheduled for `key`, after any previous task of that key has been cancelled. */\n onSchedule?: (key: K) => void;\n /** Called when the wait elapses and the task of `key` is about to run. */\n onStart?: (key: K) => void;\n /** Called when the task of `key` completes without throwing and without being cancelled. */\n onSuccess?: (key: K) => void;\n /** Called when a live task of `key` is cancelled, either explicitly or by being replaced. */\n onCancel?: (key: K) => void;\n /** Receives task errors. Cancellations never reach this callback. Defaults to `console.error`. */\n onError?: (error: unknown, key: K) => void;\n /** Called when `key` has no more pending work, after it has been removed from the debouncer. */\n onIdle?: (key: K) => void;\n}\n\n/**\n * An independent {@link Debouncer} per key.\n * Debouncers only exist for keys with pending work: each one is created when\n * its first task is scheduled and removed as soon as it becomes idle.\n *\n * @example\n * ```ts\n * const debouncer = new KeyedDebouncer<string>({delayMs: 1500});\n *\n * debouncer.schedule(chatId, async (signal) => {\n * const pending = await store.getPending(chatId);\n * const reply = await callAI(pending, {signal});\n * if (signal.aborted) return;\n * await sendReply(chatId, reply);\n * });\n * ```\n */\nexport default class KeyedDebouncer<K = string> {\n readonly #debouncers = new Map<K, Debouncer>();\n readonly #delayMs: number;\n readonly #onSchedule: (key: K) => void;\n readonly #onStart: (key: K) => void;\n readonly #onSuccess: (key: K) => void;\n readonly #onCancel: (key: K) => void;\n readonly #onError: (error: unknown, key: K) => void;\n readonly #onIdle: (key: K) => void;\n\n constructor(options: KeyedDebouncerOptions<K>) {\n assertValidDelay(options.delayMs);\n this.#delayMs = options.delayMs;\n this.#onSchedule = options.onSchedule ?? noop;\n this.#onStart = options.onStart ?? noop;\n this.#onSuccess = options.onSuccess ?? noop;\n this.#onCancel = options.onCancel ?? noop;\n this.#onError = options.onError ?? console.error;\n this.#onIdle = options.onIdle ?? noop;\n }\n\n /** Number of keys with a task waiting or running. */\n get size(): number {\n return this.#debouncers.size;\n }\n\n /**\n * Schedule `task` for `key`, cancelling any previous task of that key.\n *\n * @param key - The key whose task is replaced.\n * @param task - The task to run once the delay elapses.\n * @param delayMs - Wait for this task only. Defaults to the configured `delayMs`.\n */\n schedule(key: K, task: DebouncedTask, delayMs?: number): void {\n const existing = this.#debouncers.get(key);\n if (existing !== undefined) {\n existing.schedule(task, delayMs);\n return;\n }\n\n // Validate first so an invalid delay never registers the key.\n assertValidDelay(delayMs ?? this.#delayMs);\n const debouncer = this.#create(key);\n this.#debouncers.set(key, debouncer);\n debouncer.schedule(task, delayMs);\n }\n\n /** Cancel the task of `key`, if any. */\n cancel(key: K): void {\n this.#debouncers.get(key)?.cancel();\n }\n\n /** Cancel every task. Useful when shutting the process down. */\n cancelAll(): void {\n // Copy first: cancelling removes the debouncer from the map.\n for (const debouncer of [...this.#debouncers.values()]) {\n debouncer.cancel();\n }\n }\n\n /** Whether a task is waiting or running for `key`. */\n isPending(key: K): boolean {\n return this.#debouncers.has(key);\n }\n\n #create(key: K): Debouncer {\n const debouncer: Debouncer = new Debouncer({\n delayMs: this.#delayMs,\n onSchedule: () => this.#onSchedule(key),\n onStart: () => this.#onStart(key),\n onSuccess: () => this.#onSuccess(key),\n onCancel: () => this.#onCancel(key),\n onError: (error) => this.#onError(error, key),\n onIdle: () => {\n if (this.#debouncers.get(key) === debouncer) {\n this.#debouncers.delete(key);\n this.#onIdle(key);\n }\n },\n });\n return debouncer;\n }\n}\n"]}
@@ -301,11 +301,34 @@ export function shallowEqual(a, b) {
301
301
  /**
302
302
  * Pauses the execution of an asynchronous function for a specified duration.
303
303
  *
304
- * @param {number} ms - The delay duration in milliseconds.
305
- * @return {Promise<void>} A promise that resolves after the specified delay.
304
+ * When `signal` is provided, the returned promise rejects with `signal.reason`
305
+ * as soon as the signal is aborted (or immediately if it is already aborted),
306
+ * and the pending timer is cleared.
307
+ *
308
+ * @param ms - The delay duration in milliseconds.
309
+ * @param signal - Optional signal that cancels the wait.
310
+ * @return A promise that resolves after the specified delay.
306
311
  */
307
- export async function delay(ms) {
308
- await new Promise(resolve => setTimeout(resolve, ms));
312
+ export function delay(ms, signal) {
313
+ return new Promise((resolve, reject) => {
314
+ if (signal === undefined) {
315
+ setTimeout(resolve, ms);
316
+ return;
317
+ }
318
+ if (signal.aborted) {
319
+ reject(signal.reason);
320
+ return;
321
+ }
322
+ const onAbort = () => {
323
+ clearTimeout(timer);
324
+ reject(signal.reason);
325
+ };
326
+ const timer = setTimeout(() => {
327
+ signal.removeEventListener("abort", onAbort);
328
+ resolve();
329
+ }, ms);
330
+ signal.addEventListener("abort", onAbort, { once: true });
331
+ });
309
332
  }
310
333
  /**
311
334
  * Checks if a value is undefined.