@thainanluiz/tssuper 0.0.12 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,38 +1,74 @@
1
1
  type RandomIntProps = {
2
- min: number;
3
- max: number;
2
+ /**
3
+ * Minimum value (inclusive), a safe integer from -9007199254740991 to
4
+ * 9007199254740991. Defaults to 0 when omitted or `undefined`.
5
+ */
6
+ min?: number;
7
+ /**
8
+ * Maximum value (inclusive), a safe integer not less than `min`, with
9
+ * `max - min` at most 9007199254740991. Defaults to 10 when omitted or
10
+ * `undefined`.
11
+ */
12
+ max?: number;
4
13
  };
5
14
 
6
15
  /**
7
- * Generate a random integer between min and max (inclusive)
8
- * @param {RandomIntProps} { min, max }
16
+ * Generate a random integer between `min` and `max`, both inclusive.
9
17
  *
10
- * @returns {number}
18
+ * An omitted bound (absent or `undefined`) takes its default: 0 for `min`, 10
19
+ * for `max`. Both bounds must be safe integers, and `max - min` must be at
20
+ * most 9007199254740991. When an error compares `min` and `max` and one of
21
+ * them was omitted, its message ends with ` (max defaults to 10)` or
22
+ * ` (min defaults to 0)`.
11
23
  *
12
- * @throws {Error} min and max must be numbers
13
- * @throws {Error} min and max must be finite numbers
14
- * @throws {Error} min and max must be integers
15
- * @throws {Error} min must be less than or equal to max
24
+ * A range of up to 2^32 values uses one `Math.random()` call (any bias is
25
+ * below one in a million); a wider range uses at least two calls, and every
26
+ * integer in it is equally likely. Because the result comes from
27
+ * `Math.random()`, it is not suitable for passwords, tokens, keys or other
28
+ * security-sensitive values; use `crypto.getRandomValues()` for those.
29
+ *
30
+ * Invalid input throws a `TypeError` for a value of the wrong type and a
31
+ * `RangeError` for a value of the right type that is not allowed.
32
+ *
33
+ * @param {RandomIntProps} [props] { min = 0, max = 10 }
34
+ *
35
+ * @returns {number} A random integer from `min` to `max`.
36
+ *
37
+ * @throws {TypeError} props must be an object if defined
38
+ * @throws {TypeError | RangeError} min must be a safe integer (between -9007199254740991 and 9007199254740991)
39
+ * @throws {TypeError | RangeError} max must be a safe integer (between -9007199254740991 and 9007199254740991)
40
+ * @throws {RangeError} min must be less than or equal to max
41
+ * @throws {RangeError} max - min must be at most 9007199254740991
16
42
  */
17
- declare function randomInt({ min, max }: RandomIntProps): number;
43
+ declare function randomInt(props?: RandomIntProps): number;
18
44
 
19
45
  type FormatNumberProps = {
46
+ /** The number to be formatted. Must be finite. */
20
47
  number: number;
48
+ /** Number of decimal places to round to (integer from 0 to 100). */
21
49
  decimalPlaces: number;
22
50
  };
23
51
 
24
52
  /**
25
- * Format a number to a specific number of decimal places
26
- * @param {FormatNumberProps} { number, decimalPlaces }
53
+ * Round a number to a given number of decimal places. Halves are rounded away
54
+ * from zero based on the decimal value, so 1.005 becomes 1.01, and the result
55
+ * is never -0.
27
56
  *
28
- * @returns {number}
57
+ * Invalid input throws a `TypeError` for a value of the wrong type and a
58
+ * `RangeError` for a value of the right type that is not allowed.
29
59
  *
30
- * @throws {Error} number must be a number
31
- * @throws {Error} number must be a finite number
32
- * @throws {Error} decimalPlaces must be an integer
33
- * @throws {Error} decimalPlaces must be non-negative
60
+ * @param {FormatNumberProps} props { number, decimalPlaces }
61
+ *
62
+ * @returns {number} The rounded number.
63
+ *
64
+ * @throws {TypeError} props must be an object
65
+ * @throws {TypeError} number must be a number
66
+ * @throws {RangeError} number must be a finite number
67
+ * @throws {TypeError | RangeError} decimalPlaces must be an integer
68
+ * @throws {RangeError} decimalPlaces must be non-negative
69
+ * @throws {RangeError} decimalPlaces must be at most 100
34
70
  */
35
- declare function formatNumber({ number, decimalPlaces, }: FormatNumberProps): number;
71
+ declare function formatNumber(props: FormatNumberProps): number;
36
72
 
37
73
  type index$1_FormatNumberProps = FormatNumberProps;
38
74
  type index$1_RandomIntProps = RandomIntProps;
@@ -43,44 +79,147 @@ declare namespace index$1 {
43
79
  }
44
80
 
45
81
  type FixedDelayProps = {
82
+ /** Delay in milliseconds (positive, at most 2147483647). */
46
83
  ms: number;
84
+ /**
85
+ * Optional time in milliseconds after which the delay resolves early
86
+ * (positive, at most 2147483647). A value of `ms` or more has no effect.
87
+ */
47
88
  breakAt?: number;
89
+ /** If true, the promise resolves with the elapsed time in milliseconds. */
48
90
  returnElapsed?: boolean;
49
91
  };
50
92
 
51
93
  /**
52
- * Create a fixed delay function that returns a promise that resolves after a given number of milliseconds.
53
- * @param {FixedDelayProps} { ms, breakAt, returnElapsed }
94
+ * Wait `ms` milliseconds, or `breakAt` milliseconds if that is shorter, or
95
+ * until `cancel` is called.
96
+ *
97
+ * Invalid input throws on the call, never through the promise: a `TypeError`
98
+ * for a value of the wrong type and a `RangeError` for a value of the right
99
+ * type that is not allowed.
100
+ *
101
+ * @param {FixedDelayProps} props { ms, breakAt } with returnElapsed omitted or false
102
+ *
103
+ * @returns {object} An object containing the promise, which resolves with
104
+ * undefined when the delay ends, and a cancel function that ends it
105
+ * immediately.
106
+ *
107
+ * @throws {TypeError} props must be an object
108
+ * @throws {TypeError | RangeError} ms must be a positive number (at most 2147483647)
109
+ * @throws {TypeError | RangeError} breakAt must be a positive number if defined (at most 2147483647)
110
+ * @throws {TypeError} returnElapsed must be a boolean if defined
111
+ */
112
+ declare function fixedDelay(props: FixedDelayProps & {
113
+ returnElapsed?: false;
114
+ }): {
115
+ promise: Promise<void>;
116
+ cancel: () => void;
117
+ };
118
+ /**
119
+ * Wait `ms` milliseconds, or `breakAt` milliseconds if that is shorter, or
120
+ * until `cancel` is called.
54
121
  *
55
- * @returns {object} An object containing the promise and a cancel function
122
+ * Invalid input throws on the call, never through the promise: a `TypeError`
123
+ * for a value of the wrong type and a `RangeError` for a value of the right
124
+ * type that is not allowed.
56
125
  *
57
- * @throws {Error} ms must be a positive number
58
- * @throws {Error} breakAt must be a positive number if defined
59
- * @throws {Error} returnElapsed must be a boolean if defined
126
+ * @param {FixedDelayProps} props { ms, breakAt } with returnElapsed: true
127
+ *
128
+ * @returns {object} An object containing the promise, which resolves with the
129
+ * elapsed time in milliseconds when the delay ends, and a cancel function that
130
+ * ends it immediately.
131
+ *
132
+ * @throws {TypeError} props must be an object
133
+ * @throws {TypeError | RangeError} ms must be a positive number (at most 2147483647)
134
+ * @throws {TypeError | RangeError} breakAt must be a positive number if defined (at most 2147483647)
135
+ * @throws {TypeError} returnElapsed must be a boolean if defined
136
+ */
137
+ declare function fixedDelay(props: FixedDelayProps & {
138
+ returnElapsed: true;
139
+ }): {
140
+ promise: Promise<number>;
141
+ cancel: () => void;
142
+ };
143
+ /**
144
+ * Wait `ms` milliseconds, or `breakAt` milliseconds if that is shorter, or
145
+ * until `cancel` is called.
146
+ *
147
+ * Invalid input throws on the call, never through the promise: a `TypeError`
148
+ * for a value of the wrong type and a `RangeError` for a value of the right
149
+ * type that is not allowed.
150
+ *
151
+ * @param {FixedDelayProps} props { ms, breakAt, returnElapsed }
152
+ *
153
+ * @returns {object} An object containing the promise, which resolves when the
154
+ * delay ends with the elapsed time in milliseconds if returnElapsed is true
155
+ * (undefined otherwise), and a cancel function that ends it immediately.
156
+ *
157
+ * @throws {TypeError} props must be an object
158
+ * @throws {TypeError | RangeError} ms must be a positive number (at most 2147483647)
159
+ * @throws {TypeError | RangeError} breakAt must be a positive number if defined (at most 2147483647)
160
+ * @throws {TypeError} returnElapsed must be a boolean if defined
60
161
  */
61
- declare function fixedDelay({ ms, breakAt, returnElapsed }: FixedDelayProps): {
162
+ declare function fixedDelay(props: FixedDelayProps): {
62
163
  promise: Promise<number | void>;
63
164
  cancel: () => void;
64
165
  };
65
166
 
66
167
  type FixedRepeaterProps = {
67
- callback: () => void;
168
+ /**
169
+ * Function called on every repetition. It can be async: if it returns a
170
+ * promise or another thenable (an object with a `then` method), the next
171
+ * call starts `ms` after this one started or as soon as that promise
172
+ * settles, whichever is later, so calls never overlap. If the callback
173
+ * throws or its promise rejects, the repetitions stop and the returned
174
+ * promise rejects with that error.
175
+ */
176
+ callback: () => unknown;
177
+ /**
178
+ * Time in milliseconds from the start of one call to the start of the next
179
+ * (positive, at most 2147483647). The first call happens `ms` after
180
+ * `fixedRepeater` is called. A call that takes longer than `ms`, including
181
+ * its promise, delays the next one until it finishes.
182
+ */
68
183
  ms: number;
184
+ /** Number of times the callback is called (positive integer, at most 9007199254740991). */
69
185
  times: number;
70
186
  };
71
187
 
72
188
  /**
73
- * Create a fixed repeater function that calls a given function a given number of times with a fixed delay between each call.
74
- * @param {FixedRepeaterProps} { callback, ms, times }
189
+ * Call a function a fixed number of times at a fixed interval, without
190
+ * overlapping calls.
191
+ *
192
+ * The first call happens `ms` after `fixedRepeater` is called, and each
193
+ * following call starts `ms` after the previous one started. A call that takes
194
+ * longer than `ms` delays the next one, which then starts as soon as it
195
+ * finishes. If the callback returns a promise or another thenable (an object
196
+ * with a `then` method), the call finishes when that promise settles, so calls
197
+ * never overlap. If a callback promise never settles, the repeater waits
198
+ * forever; call `cancel` to stop it.
75
199
  *
76
- * @returns {object} An object containing the promise and a cancel function
200
+ * Invalid input throws on the call, never through the promise: a `TypeError`
201
+ * for a value of the wrong type and a `RangeError` for a value of the right
202
+ * type that is not allowed.
77
203
  *
78
- * @throws {Error} callback must be a function
79
- * @throws {Error} ms must be a positive number
80
- * @throws {Error} times must be a positive number
204
+ * @param {FixedRepeaterProps} props { callback, ms, times }
205
+ *
206
+ * @returns {object} An object containing the promise and a cancel function.
207
+ * The promise resolves with the number of calls made once the last call has
208
+ * finished (including its promise). If the callback throws or its promise
209
+ * rejects, the repetitions stop and the promise rejects with that error.
210
+ * `cancel` stops the repetitions and resolves the promise right away with the
211
+ * number of calls made so far, counting a call still in progress. Nothing that
212
+ * call does afterwards changes the result: a promise it returned is not
213
+ * awaited and is ignored even if it rejects, and an error it throws after
214
+ * calling `cancel` is ignored.
215
+ *
216
+ * @throws {TypeError} props must be an object
217
+ * @throws {TypeError} callback must be a function
218
+ * @throws {TypeError | RangeError} ms must be a positive number (at most 2147483647)
219
+ * @throws {TypeError | RangeError} times must be a positive integer (at most 9007199254740991)
81
220
  */
82
- declare function fixedRepeater({ callback, ms, times }: FixedRepeaterProps): {
83
- promise: Promise<number | void>;
221
+ declare function fixedRepeater(props: FixedRepeaterProps): {
222
+ promise: Promise<number>;
84
223
  cancel: () => void;
85
224
  };
86
225
 
package/dist/index.js CHANGED
@@ -1,2 +1,247 @@
1
- "use strict";var s=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var d=(r,e)=>{for(var o in e)s(r,o,{get:e[o],enumerable:!0})},h=(r,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of y(e))!v.call(r,n)&&n!==o&&s(r,n,{get:()=>e[n],enumerable:!(t=P(e,n))||t.enumerable});return r};var I=r=>h(s({},"__esModule",{value:!0}),r);var F={};d(F,{delay:()=>p,math:()=>a});module.exports=I(F);var a={};d(a,{formatNumber:()=>w,randomInt:()=>b});function b({min:r,max:e}){if(typeof r!="number"||typeof e!="number")throw new Error("min and max must be numbers");if(!isFinite(r)||!isFinite(e))throw new Error("min and max must be finite numbers");if(!Number.isInteger(r)||!Number.isInteger(e))throw new Error("min and max must be integers");if(r>e)throw new Error("min must be less than or equal to max");return Math.floor(Math.random()*(e-r+1))+r}function w({number:r,decimalPlaces:e}){if(typeof r!="number")throw new Error("number must be a number");if(!isFinite(r))throw new Error("number must be a finite number");if(!Number.isInteger(e))throw new Error("decimalPlaces must be an integer");if(e<0)throw new Error("decimalPlaces must be non-negative");return Number(r.toFixed(e))}var p={};d(p,{fixedDelay:()=>l,fixedRepeater:()=>x});function l({ms:r,breakAt:e,returnElapsed:o}){if(typeof r!="number"||r<=0)throw new Error("ms must be a positive number");if(e!==void 0&&(typeof e!="number"||e<=0))throw new Error("breakAt must be a positive number if defined");if(o!==void 0&&typeof o!="boolean")throw new Error("returnElapsed must be a boolean if defined");let t,n,m=Date.now(),f;return{promise:new Promise(u=>{f=u,t=setTimeout(()=>{o?u(Date.now()-m):u()},r),e&&(n=setTimeout(()=>{clearTimeout(t),u(o?Date.now()-m:void 0)},e))}),cancel:()=>{clearTimeout(t),e&&clearTimeout(n),f(o?Date.now()-m:void 0)}}}function x({callback:r,ms:e,times:o}){if(typeof r!="function")throw new Error("callback must be a function");if(typeof e!="number"||e<=0)throw new Error("ms must be a positive number");if(typeof o!="number"||o<=0)throw new Error("times must be a positive number");let t=0,n=!1,m,f;return{promise:new Promise(u=>{f=u,m=setInterval(()=>{if(n){clearInterval(m),u(t);return}r(),t++,t>=o&&(clearInterval(m),u(t))},e)}),cancel:()=>{n=!0,clearInterval(m),f(t)}}}0&&(module.exports={delay,math});
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ delay: () => delay_exports,
24
+ math: () => math_exports
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/math/index.ts
29
+ var math_exports = {};
30
+ __export(math_exports, {
31
+ formatNumber: () => formatNumber,
32
+ randomInt: () => randomInt
33
+ });
34
+
35
+ // src/utils/isProps.ts
36
+ var PROPS_MESSAGE = "props must be an object";
37
+ function isProps(value) {
38
+ return typeof value === "object" && value !== null && !Array.isArray(value);
39
+ }
40
+
41
+ // src/math/utils/randomIndex.ts
42
+ var TWO_POW_21 = 2 ** 21;
43
+ var TWO_POW_32 = 2 ** 32;
44
+ var TWO_POW_53 = 2 ** 53;
45
+ var MAX_ATTEMPTS = 64;
46
+ function randomIndex(n) {
47
+ if (n <= TWO_POW_32) return Math.floor(Math.random() * n);
48
+ const limit = TWO_POW_53 - TWO_POW_53 % n;
49
+ let value = 0;
50
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
51
+ value = Math.floor(Math.random() * TWO_POW_21) * TWO_POW_32 + Math.floor(Math.random() * TWO_POW_32);
52
+ if (value < limit) break;
53
+ }
54
+ return value % n;
55
+ }
56
+
57
+ // src/math/functions/randomInt.ts
58
+ var DEFAULT_MIN = 0;
59
+ var DEFAULT_MAX = 10;
60
+ var MAX_SAFE = Number.MAX_SAFE_INTEGER;
61
+ var SAFE_RANGE = `between ${-MAX_SAFE} and ${MAX_SAFE}`;
62
+ function randomInt(props = {}) {
63
+ if (!isProps(props)) {
64
+ throw new TypeError(`${PROPS_MESSAGE} if defined`);
65
+ }
66
+ const { min: givenMin, max: givenMax } = props;
67
+ const min = givenMin === void 0 ? DEFAULT_MIN : givenMin;
68
+ const max = givenMax === void 0 ? DEFAULT_MAX : givenMax;
69
+ if (!Number.isSafeInteger(min)) {
70
+ const message = `min must be a safe integer (${SAFE_RANGE})`;
71
+ throw typeof min === "number" ? new RangeError(message) : new TypeError(message);
72
+ }
73
+ if (!Number.isSafeInteger(max)) {
74
+ const message = `max must be a safe integer (${SAFE_RANGE})`;
75
+ throw typeof max === "number" ? new RangeError(message) : new TypeError(message);
76
+ }
77
+ const defaultNote = givenMax === void 0 ? ` (max defaults to ${DEFAULT_MAX})` : givenMin === void 0 ? ` (min defaults to ${DEFAULT_MIN})` : "";
78
+ if (min > max) {
79
+ throw new RangeError(`min must be less than or equal to max${defaultNote}`);
80
+ }
81
+ if (max - min > MAX_SAFE) {
82
+ throw new RangeError(`max - min must be at most ${MAX_SAFE}${defaultNote}`);
83
+ }
84
+ return min + randomIndex(max - min + 1);
85
+ }
86
+
87
+ // src/math/functions/formatNumber.ts
88
+ var MAX_DECIMAL_PLACES = 100;
89
+ function shiftDecimalPoint(value, places) {
90
+ const [mantissa, exponent = "0"] = String(value).split("e");
91
+ return Number(`${mantissa}e${Number(exponent) + places}`);
92
+ }
93
+ function formatNumber(props) {
94
+ if (!isProps(props)) {
95
+ throw new TypeError(PROPS_MESSAGE);
96
+ }
97
+ const { number, decimalPlaces } = props;
98
+ if (typeof number !== "number") {
99
+ throw new TypeError("number must be a number");
100
+ }
101
+ if (!Number.isFinite(number)) {
102
+ throw new RangeError("number must be a finite number");
103
+ }
104
+ if (!Number.isInteger(decimalPlaces)) {
105
+ const message = "decimalPlaces must be an integer";
106
+ throw typeof decimalPlaces === "number" ? new RangeError(message) : new TypeError(message);
107
+ }
108
+ if (decimalPlaces < 0) {
109
+ throw new RangeError("decimalPlaces must be non-negative");
110
+ }
111
+ if (decimalPlaces > MAX_DECIMAL_PLACES) {
112
+ throw new RangeError(`decimalPlaces must be at most ${MAX_DECIMAL_PLACES}`);
113
+ }
114
+ if (Number.isInteger(number)) {
115
+ return number === 0 ? 0 : number;
116
+ }
117
+ const rounded = Math.round(
118
+ shiftDecimalPoint(Math.abs(number), decimalPlaces)
119
+ );
120
+ const result = Math.sign(number) * shiftDecimalPoint(rounded, -decimalPlaces);
121
+ return result === 0 ? 0 : result;
122
+ }
123
+
124
+ // src/delay/index.ts
125
+ var delay_exports = {};
126
+ __export(delay_exports, {
127
+ fixedDelay: () => fixedDelay,
128
+ fixedRepeater: () => fixedRepeater
129
+ });
130
+
131
+ // src/delay/utils/isValidDelay.ts
132
+ var MAX_DELAY_MS = 2147483647;
133
+ var MS_MESSAGE = `ms must be a positive number (at most ${MAX_DELAY_MS})`;
134
+ function isValidDelay(value) {
135
+ return typeof value === "number" && value > 0 && value <= MAX_DELAY_MS;
136
+ }
137
+
138
+ // src/delay/functions/fixedDelay.ts
139
+ var BREAK_AT_MESSAGE = `breakAt must be a positive number if defined (at most ${MAX_DELAY_MS})`;
140
+ function fixedDelay(props) {
141
+ if (!isProps(props)) {
142
+ throw new TypeError(PROPS_MESSAGE);
143
+ }
144
+ const { ms, breakAt, returnElapsed } = props;
145
+ if (!isValidDelay(ms)) {
146
+ throw typeof ms === "number" ? new RangeError(MS_MESSAGE) : new TypeError(MS_MESSAGE);
147
+ }
148
+ if (breakAt !== void 0 && !isValidDelay(breakAt)) {
149
+ throw typeof breakAt === "number" ? new RangeError(BREAK_AT_MESSAGE) : new TypeError(BREAK_AT_MESSAGE);
150
+ }
151
+ if (returnElapsed !== void 0 && typeof returnElapsed !== "boolean") {
152
+ throw new TypeError("returnElapsed must be a boolean if defined");
153
+ }
154
+ const startTime = Date.now();
155
+ let timeoutId;
156
+ let breakTimeoutId;
157
+ let finish;
158
+ const promise = new Promise((resolve) => {
159
+ finish = () => {
160
+ clearTimeout(timeoutId);
161
+ clearTimeout(breakTimeoutId);
162
+ resolve(returnElapsed ? Date.now() - startTime : void 0);
163
+ };
164
+ });
165
+ timeoutId = setTimeout(finish, ms);
166
+ if (breakAt !== void 0) {
167
+ breakTimeoutId = setTimeout(finish, breakAt);
168
+ }
169
+ return { promise, cancel: finish };
170
+ }
171
+
172
+ // src/delay/utils/isPromiseLike.ts
173
+ function isPromiseLike(value) {
174
+ return value != null && typeof value.then === "function";
175
+ }
176
+
177
+ // src/delay/functions/fixedRepeater.ts
178
+ var TIMES_MESSAGE = `times must be a positive integer (at most ${Number.MAX_SAFE_INTEGER})`;
179
+ function fixedRepeater(props) {
180
+ if (!isProps(props)) {
181
+ throw new TypeError(PROPS_MESSAGE);
182
+ }
183
+ const { callback, ms, times } = props;
184
+ if (typeof callback !== "function") {
185
+ throw new TypeError("callback must be a function");
186
+ }
187
+ if (!isValidDelay(ms)) {
188
+ throw typeof ms === "number" ? new RangeError(MS_MESSAGE) : new TypeError(MS_MESSAGE);
189
+ }
190
+ if (!Number.isSafeInteger(times) || times <= 0) {
191
+ throw typeof times === "number" ? new RangeError(TIMES_MESSAGE) : new TypeError(TIMES_MESSAGE);
192
+ }
193
+ let count = 0;
194
+ let settled = false;
195
+ let startedAt = 0;
196
+ let timeoutId;
197
+ let resolvePromise;
198
+ let rejectPromise;
199
+ const promise = new Promise((resolve, reject) => {
200
+ resolvePromise = resolve;
201
+ rejectPromise = reject;
202
+ });
203
+ const settle = (outcome) => {
204
+ if (settled) return;
205
+ settled = true;
206
+ clearTimeout(timeoutId);
207
+ outcome();
208
+ };
209
+ const fail = (error) => settle(() => rejectPromise(error));
210
+ const next = () => {
211
+ if (settled) return;
212
+ if (count >= times) {
213
+ settle(() => resolvePromise(count));
214
+ return;
215
+ }
216
+ const elapsed = Math.min(Math.max(Date.now() - startedAt, 0), ms);
217
+ timeoutId = setTimeout(run, ms - elapsed);
218
+ };
219
+ const run = () => {
220
+ count++;
221
+ startedAt = Date.now();
222
+ let pending;
223
+ try {
224
+ const result = callback();
225
+ if (isPromiseLike(result)) pending = result;
226
+ } catch (error) {
227
+ fail(error);
228
+ return;
229
+ }
230
+ if (pending) {
231
+ Promise.resolve(pending).then(next, fail);
232
+ } else {
233
+ next();
234
+ }
235
+ };
236
+ timeoutId = setTimeout(run, ms);
237
+ return {
238
+ promise,
239
+ cancel: () => settle(() => resolvePromise(count))
240
+ };
241
+ }
242
+ // Annotate the CommonJS export names for ESM import in node:
243
+ 0 && (module.exports = {
244
+ delay,
245
+ math
246
+ });
2
247
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/math/index.ts","../src/math/functions/randomInt.ts","../src/math/functions/formatNumber.ts","../src/delay/index.ts","../src/delay/functions/fixedDelay.ts","../src/delay/functions/fixedRepeater.ts"],"sourcesContent":["export * as math from \"./math\";\r\nexport * as delay from \"./delay\";\r\n","export * from \"./functions\";\r\nexport * from \"./types\";\r\n","import { RandomIntProps } from \"../types/randomIntProps\";\r\n\r\n/**\r\n * Generate a random integer between min and max (inclusive)\r\n * @param {RandomIntProps} { min, max }\r\n *\r\n * @returns {number}\r\n *\r\n * @throws {Error} min and max must be numbers\r\n * @throws {Error} min and max must be finite numbers\r\n * @throws {Error} min and max must be integers\r\n * @throws {Error} min must be less than or equal to max\r\n */\r\nexport function randomInt({ min, max }: RandomIntProps): number {\r\n // Validate that min and max are numbers\r\n if (typeof min !== \"number\" || typeof max !== \"number\") {\r\n throw new Error(\"min and max must be numbers\");\r\n }\r\n\r\n // Validate that min and max are finite numbers\r\n if (!isFinite(min) || !isFinite(max)) {\r\n throw new Error(\"min and max must be finite numbers\");\r\n }\r\n\r\n // Validate that min and max are integers\r\n if (!Number.isInteger(min) || !Number.isInteger(max)) {\r\n throw new Error(\"min and max must be integers\");\r\n }\r\n\r\n // Validate that min is less than or equal to max\r\n if (min > max) {\r\n throw new Error(\"min must be less than or equal to max\");\r\n }\r\n\r\n // Generate a random integer between min and max\r\n return Math.floor(Math.random() * (max - min + 1)) + min;\r\n}\r\n","import { FormatNumberProps } from \"../types/formatNumberProps\";\r\n\r\n/**\r\n * Format a number to a specific number of decimal places\r\n * @param {FormatNumberProps} { number, decimalPlaces }\r\n *\r\n * @returns {number}\r\n *\r\n * @throws {Error} number must be a number\r\n * @throws {Error} number must be a finite number\r\n * @throws {Error} decimalPlaces must be an integer\r\n * @throws {Error} decimalPlaces must be non-negative\r\n */\r\nexport function formatNumber({\r\n number,\r\n decimalPlaces,\r\n}: FormatNumberProps): number {\r\n // Validate that number is a number\r\n if (typeof number !== \"number\") {\r\n throw new Error(\"number must be a number\");\r\n }\r\n\r\n // Validate that number is a finite number\r\n if (!isFinite(number)) {\r\n throw new Error(\"number must be a finite number\");\r\n }\r\n\r\n // Validate that decimalPlaces is an integer\r\n if (!Number.isInteger(decimalPlaces)) {\r\n throw new Error(\"decimalPlaces must be an integer\");\r\n }\r\n\r\n // Validate that decimalPlaces is non-negative\r\n if (decimalPlaces < 0) {\r\n throw new Error(\"decimalPlaces must be non-negative\");\r\n }\r\n\r\n // Format the number to the specified number of decimal places\r\n return Number(number.toFixed(decimalPlaces));\r\n}\r\n","export * from \"./functions\";\r\nexport * from \"./types\";\r\n","import { FixedDelayProps } from \"./../types/fixedDelayProps\";\r\n\r\n/**\r\n * Create a fixed delay function that returns a promise that resolves after a given number of milliseconds.\r\n * @param {FixedDelayProps} { ms, breakAt, returnElapsed }\r\n *\r\n * @returns {object} An object containing the promise and a cancel function\r\n *\r\n * @throws {Error} ms must be a positive number\r\n * @throws {Error} breakAt must be a positive number if defined\r\n * @throws {Error} returnElapsed must be a boolean if defined\r\n */\r\nexport function fixedDelay({ ms, breakAt, returnElapsed }: FixedDelayProps): {\r\n promise: Promise<number | void>;\r\n cancel: () => void;\r\n} {\r\n // Validate that ms is a positive number\r\n if (typeof ms !== \"number\" || ms <= 0) {\r\n throw new Error(\"ms must be a positive number\");\r\n }\r\n\r\n // Validate that breakAt is a positive number if defined\r\n if (breakAt !== undefined && (typeof breakAt !== \"number\" || breakAt <= 0)) {\r\n throw new Error(\"breakAt must be a positive number if defined\");\r\n }\r\n\r\n // Validate that returnElapsed is a boolean if defined\r\n if (returnElapsed !== undefined && typeof returnElapsed !== \"boolean\") {\r\n throw new Error(\"returnElapsed must be a boolean if defined\");\r\n }\r\n\r\n let timeoutId: NodeJS.Timeout;\r\n let breakTimeoutId: NodeJS.Timeout;\r\n const startTime = Date.now();\r\n let resolvePromise: (value?: number | void) => void;\r\n\r\n const promise = new Promise<number | void>((resolve) => {\r\n resolvePromise = resolve;\r\n\r\n timeoutId = setTimeout(() => {\r\n if (returnElapsed) {\r\n resolve(Date.now() - startTime);\r\n } else {\r\n resolve();\r\n }\r\n }, ms);\r\n\r\n if (breakAt) {\r\n breakTimeoutId = setTimeout(() => {\r\n clearTimeout(timeoutId);\r\n resolve(returnElapsed ? Date.now() - startTime : undefined);\r\n }, breakAt);\r\n }\r\n });\r\n\r\n // Return the promise and a cancel function\r\n return {\r\n promise,\r\n cancel: () => {\r\n clearTimeout(timeoutId);\r\n if (breakAt) {\r\n clearTimeout(breakTimeoutId);\r\n }\r\n resolvePromise(returnElapsed ? Date.now() - startTime : undefined);\r\n },\r\n };\r\n}\r\n","import { FixedRepeaterProps } from \"./../types/fixedRepeaterProps\";\r\n\r\n/**\r\n * Create a fixed repeater function that calls a given function a given number of times with a fixed delay between each call.\r\n * @param {FixedRepeaterProps} { callback, ms, times }\r\n *\r\n * @returns {object} An object containing the promise and a cancel function\r\n *\r\n * @throws {Error} callback must be a function\r\n * @throws {Error} ms must be a positive number\r\n * @throws {Error} times must be a positive number\r\n */\r\nexport function fixedRepeater({ callback, ms, times }: FixedRepeaterProps): {\r\n promise: Promise<number | void>;\r\n cancel: () => void;\r\n} {\r\n // Validate that callback is a function\r\n if (typeof callback !== \"function\") {\r\n throw new Error(\"callback must be a function\");\r\n }\r\n\r\n // Validate that ms is a positive number\r\n if (typeof ms !== \"number\" || ms <= 0) {\r\n throw new Error(\"ms must be a positive number\");\r\n }\r\n\r\n // Validate that times is a positive number\r\n if (typeof times !== \"number\" || times <= 0) {\r\n throw new Error(\"times must be a positive number\");\r\n }\r\n\r\n let count = 0;\r\n let canceled = false;\r\n let intervalId: NodeJS.Timeout;\r\n\r\n let resolvePromise: (value?: number | void) => void;\r\n\r\n const promise = new Promise<number | void>((resolve) => {\r\n resolvePromise = resolve;\r\n\r\n intervalId = setInterval(() => {\r\n if (canceled) {\r\n clearInterval(intervalId);\r\n resolve(count);\r\n return;\r\n }\r\n\r\n callback();\r\n count++;\r\n\r\n if (count >= times) {\r\n clearInterval(intervalId);\r\n resolve(count);\r\n }\r\n }, ms);\r\n });\r\n\r\n // Return the promise and a cancel function\r\n return {\r\n promise,\r\n cancel: () => {\r\n canceled = true;\r\n clearInterval(intervalId);\r\n resolvePromise(count);\r\n },\r\n };\r\n}\r\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,WAAAE,EAAA,SAAAC,IAAA,eAAAC,EAAAJ,GCAA,IAAAK,EA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D,IAAIC,EACAC,EACEC,EAAY,KAAK,IAAI,EACvBC,EAsBJ,MAAO,CACL,QArBc,IAAI,QAAwBC,GAAY,CACtDD,EAAiBC,EAEjBJ,EAAY,WAAW,IAAM,CACvBD,EACFK,EAAQ,KAAK,IAAI,EAAIF,CAAS,EAE9BE,EAAQ,CAEZ,EAAGP,CAAE,EAEDC,IACFG,EAAiB,WAAW,IAAM,CAChC,aAAaD,CAAS,EACtBI,EAAQL,EAAgB,KAAK,IAAI,EAAIG,EAAY,MAAS,CAC5D,EAAGJ,CAAO,EAEd,CAAC,EAKC,OAAQ,IAAM,CACZ,aAAaE,CAAS,EAClBF,GACF,aAAaG,CAAc,EAE7BE,EAAeJ,EAAgB,KAAK,IAAI,EAAIG,EAAY,MAAS,CACnE,CACF,CACF,CCtDO,SAASG,EAAc,CAAE,SAAAC,EAAU,GAAAC,EAAI,MAAAC,CAAM,EAGlD,CAEA,GAAI,OAAOF,GAAa,WACtB,MAAM,IAAI,MAAM,6BAA6B,EAI/C,GAAI,OAAOC,GAAO,UAAYA,GAAM,EAClC,MAAM,IAAI,MAAM,8BAA8B,EAIhD,GAAI,OAAOC,GAAU,UAAYA,GAAS,EACxC,MAAM,IAAI,MAAM,iCAAiC,EAGnD,IAAIC,EAAQ,EACRC,EAAW,GACXC,EAEAC,EAuBJ,MAAO,CACL,QAtBc,IAAI,QAAwBC,GAAY,CACtDD,EAAiBC,EAEjBF,EAAa,YAAY,IAAM,CAC7B,GAAID,EAAU,CACZ,cAAcC,CAAU,EACxBE,EAAQJ,CAAK,EACb,MACF,CAEAH,EAAS,EACTG,IAEIA,GAASD,IACX,cAAcG,CAAU,EACxBE,EAAQJ,CAAK,EAEjB,EAAGF,CAAE,CACP,CAAC,EAKC,OAAQ,IAAM,CACZG,EAAW,GACX,cAAcC,CAAU,EACxBC,EAAeH,CAAK,CACtB,CACF,CACF","names":["src_exports","__export","delay_exports","math_exports","__toCommonJS","math_exports","__export","formatNumber","randomInt","randomInt","min","max","formatNumber","number","decimalPlaces","delay_exports","__export","fixedDelay","fixedRepeater","fixedDelay","ms","breakAt","returnElapsed","timeoutId","breakTimeoutId","startTime","resolvePromise","resolve","fixedRepeater","callback","ms","times","count","canceled","intervalId","resolvePromise","resolve"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/math/index.ts","../src/utils/isProps.ts","../src/math/utils/randomIndex.ts","../src/math/functions/randomInt.ts","../src/math/functions/formatNumber.ts","../src/delay/index.ts","../src/delay/utils/isValidDelay.ts","../src/delay/functions/fixedDelay.ts","../src/delay/utils/isPromiseLike.ts","../src/delay/functions/fixedRepeater.ts"],"sourcesContent":["export * as math from \"./math\";\nexport * as delay from \"./delay\";\n","export * from \"./functions\";\nexport * from \"./types\";\n","/** Error message for a value that cannot be used as a props object. */\nexport const PROPS_MESSAGE = \"props must be an object\";\n\n/**\n * Check whether a value can be used as the props object of a library\n * function: any object except null and arrays. Primitives (undefined\n * included) and functions are rejected. Objects without a prototype and class\n * instances are accepted, because the fields are read by destructuring.\n */\nexport function isProps(value: unknown): value is object {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","const TWO_POW_21 = 2 ** 21;\nconst TWO_POW_32 = 2 ** 32;\nconst TWO_POW_53 = 2 ** 53;\n\n/**\n * Most 53-bit draws to try before giving up, so a broken or constant\n * Math.random cannot loop forever.\n */\nconst MAX_ATTEMPTS = 64;\n\n/**\n * Pick a random integer from 0 to n - 1. `n` must be an integer from 1 to\n * 2^53.\n *\n * Up to 2^32 values: one Math.random call, `floor(Math.random() * n)`, with a\n * bias of at most n / 2^52 (below one in a million). Above that: rejection\n * sampling over a 53-bit integer built from two calls per draw, so every value\n * is equally likely.\n */\nexport function randomIndex(n: number): number {\n // Up to 2^32 values, a single draw scaled to n is uniform in practice: the\n // bias is at most n / 2^52 (below 1e-6), and the result is the same as\n // before for every Math.random value. No shortcut for n = 1: it still\n // makes one call, so the sequence of Math.random calls stays predictable.\n if (n <= TWO_POW_32) return Math.floor(Math.random() * n);\n\n // Above that, one draw does not have enough bits: build a uniform 53-bit\n // integer from the top bits of two draws (21 + 32 bits) and reject the\n // uneven tail, every value at or above limit, the largest multiple of n\n // not exceeding 2^53. The values below limit split evenly into n groups,\n // so every result is equally likely. Every intermediate value is an\n // integer up to 2^53, so all the arithmetic is exact.\n const limit = TWO_POW_53 - (TWO_POW_53 % n);\n let value = 0;\n\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n value =\n Math.floor(Math.random() * TWO_POW_21) * TWO_POW_32 +\n Math.floor(Math.random() * TWO_POW_32);\n if (value < limit) break;\n }\n\n // Without a break, all 64 draws were rejected, which a working Math.random\n // does with probability below 2^-64: the last draw is used, slightly biased\n // but in range, instead of looping forever\n return value % n;\n}\n","import { PROPS_MESSAGE, isProps } from \"../../utils/isProps\";\nimport type { RandomIntProps } from \"../types/randomIntProps\";\nimport { randomIndex } from \"../utils/randomIndex\";\n\nconst DEFAULT_MIN = 0;\nconst DEFAULT_MAX = 10;\nconst MAX_SAFE = Number.MAX_SAFE_INTEGER;\nconst SAFE_RANGE = `between ${-MAX_SAFE} and ${MAX_SAFE}`;\n\n/**\n * Generate a random integer between `min` and `max`, both inclusive.\n *\n * An omitted bound (absent or `undefined`) takes its default: 0 for `min`, 10\n * for `max`. Both bounds must be safe integers, and `max - min` must be at\n * most 9007199254740991. When an error compares `min` and `max` and one of\n * them was omitted, its message ends with ` (max defaults to 10)` or\n * ` (min defaults to 0)`.\n *\n * A range of up to 2^32 values uses one `Math.random()` call (any bias is\n * below one in a million); a wider range uses at least two calls, and every\n * integer in it is equally likely. Because the result comes from\n * `Math.random()`, it is not suitable for passwords, tokens, keys or other\n * security-sensitive values; use `crypto.getRandomValues()` for those.\n *\n * Invalid input throws a `TypeError` for a value of the wrong type and a\n * `RangeError` for a value of the right type that is not allowed.\n *\n * @param {RandomIntProps} [props] { min = 0, max = 10 }\n *\n * @returns {number} A random integer from `min` to `max`.\n *\n * @throws {TypeError} props must be an object if defined\n * @throws {TypeError | RangeError} min must be a safe integer (between -9007199254740991 and 9007199254740991)\n * @throws {TypeError | RangeError} max must be a safe integer (between -9007199254740991 and 9007199254740991)\n * @throws {RangeError} min must be less than or equal to max\n * @throws {RangeError} max - min must be at most 9007199254740991\n */\nexport function randomInt(props: RandomIntProps = {}): number {\n // Validate props before reading it: destructuring null would throw the\n // engine's own TypeError, whose text differs between engines\n if (!isProps(props)) {\n throw new TypeError(`${PROPS_MESSAGE} if defined`);\n }\n\n // An omitted bound (absent or undefined) takes its default\n const { min: givenMin, max: givenMax } = props;\n const min = givenMin === undefined ? DEFAULT_MIN : givenMin;\n const max = givenMax === undefined ? DEFAULT_MAX : givenMax;\n\n // Each bound must be a safe integer: a value of the wrong type is a\n // TypeError, a number that is not a safe integer is a RangeError\n if (!Number.isSafeInteger(min)) {\n const message = `min must be a safe integer (${SAFE_RANGE})`;\n throw typeof min === \"number\"\n ? new RangeError(message)\n : new TypeError(message);\n }\n\n if (!Number.isSafeInteger(max)) {\n const message = `max must be a safe integer (${SAFE_RANGE})`;\n throw typeof max === \"number\"\n ? new RangeError(message)\n : new TypeError(message);\n }\n\n // An error about the relation between the bounds explains the default of\n // an omitted one (both omitted always pass)\n const defaultNote =\n givenMax === undefined\n ? ` (max defaults to ${DEFAULT_MAX})`\n : givenMin === undefined\n ? ` (min defaults to ${DEFAULT_MIN})`\n : \"\";\n\n if (min > max) {\n throw new RangeError(`min must be less than or equal to max${defaultNote}`);\n }\n\n // With safe bounds, the true difference is an integer up to about 2^54, and\n // any value above MAX_SAFE rounds to at least 2^53, so this check is exact\n if (max - min > MAX_SAFE) {\n throw new RangeError(`max - min must be at most ${MAX_SAFE}${defaultNote}`);\n }\n\n // max - min + 1 is at most 2^53, so it is exact, and so is the sum: the\n // result is a safe integer. Adding min to a +0 offset never gives -0.\n return min + randomIndex(max - min + 1);\n}\n","import { PROPS_MESSAGE, isProps } from \"../../utils/isProps\";\nimport type { FormatNumberProps } from \"../types/formatNumberProps\";\n\nconst MAX_DECIMAL_PLACES = 100;\n\n/**\n * Move the decimal point of a number by editing its exponent in decimal\n * notation, avoiding the binary floating-point error of multiplying by a\n * power of ten (e.g. 1.005 * 100 === 100.49999999999999).\n */\nfunction shiftDecimalPoint(value: number, places: number): number {\n const [mantissa, exponent = \"0\"] = String(value).split(\"e\");\n return Number(`${mantissa}e${Number(exponent) + places}`);\n}\n\n/**\n * Round a number to a given number of decimal places. Halves are rounded away\n * from zero based on the decimal value, so 1.005 becomes 1.01, and the result\n * is never -0.\n *\n * Invalid input throws a `TypeError` for a value of the wrong type and a\n * `RangeError` for a value of the right type that is not allowed.\n *\n * @param {FormatNumberProps} props { number, decimalPlaces }\n *\n * @returns {number} The rounded number.\n *\n * @throws {TypeError} props must be an object\n * @throws {TypeError} number must be a number\n * @throws {RangeError} number must be a finite number\n * @throws {TypeError | RangeError} decimalPlaces must be an integer\n * @throws {RangeError} decimalPlaces must be non-negative\n * @throws {RangeError} decimalPlaces must be at most 100\n */\nexport function formatNumber(props: FormatNumberProps): number {\n // Validate props before reading it: destructuring null or undefined would\n // throw the engine's own TypeError, whose text differs between engines\n if (!isProps(props)) {\n throw new TypeError(PROPS_MESSAGE);\n }\n\n const { number, decimalPlaces } = props;\n\n // Validate that number is a number\n if (typeof number !== \"number\") {\n throw new TypeError(\"number must be a number\");\n }\n\n // Validate that number is a finite number\n if (!Number.isFinite(number)) {\n throw new RangeError(\"number must be a finite number\");\n }\n\n // Validate that decimalPlaces is an integer: a value of the wrong type is a\n // TypeError, a number that is not an integer (NaN, Infinity, 2.5) a RangeError\n if (!Number.isInteger(decimalPlaces)) {\n const message = \"decimalPlaces must be an integer\";\n throw typeof decimalPlaces === \"number\"\n ? new RangeError(message)\n : new TypeError(message);\n }\n\n // Validate that decimalPlaces is non-negative\n if (decimalPlaces < 0) {\n throw new RangeError(\"decimalPlaces must be non-negative\");\n }\n\n // Validate that decimalPlaces is within the supported range\n if (decimalPlaces > MAX_DECIMAL_PLACES) {\n throw new RangeError(`decimalPlaces must be at most ${MAX_DECIMAL_PLACES}`);\n }\n\n // Integers have nothing to round (this includes every number >= 2^53)\n if (Number.isInteger(number)) {\n return number === 0 ? 0 : number;\n }\n\n // Round the absolute value so halves are rounded away from zero\n const rounded = Math.round(\n shiftDecimalPoint(Math.abs(number), decimalPlaces)\n );\n const result = Math.sign(number) * shiftDecimalPoint(rounded, -decimalPlaces);\n\n // Normalize -0 (e.g. -0.001 rounded to 2 places) to 0\n return result === 0 ? 0 : result;\n}\n","export * from \"./functions\";\nexport * from \"./types\";\n","/**\n * Largest delay accepted by setTimeout/setInterval (2^31 - 1 ms, ~24.8 days).\n * Bigger values overflow and the timer fires almost at once instead (after\n * 1 ms in Node.js).\n */\nexport const MAX_DELAY_MS = 2147483647;\n\n/** Error message for an invalid `ms`, shared by fixedDelay and fixedRepeater. */\nexport const MS_MESSAGE = `ms must be a positive number (at most ${MAX_DELAY_MS})`;\n\n/**\n * Check that a value can be safely used as a timer delay: a positive number\n * no greater than MAX_DELAY_MS (rejects NaN and Infinity).\n */\nexport function isValidDelay(value: unknown): value is number {\n return typeof value === \"number\" && value > 0 && value <= MAX_DELAY_MS;\n}\n","import { PROPS_MESSAGE, isProps } from \"../../utils/isProps\";\nimport type { FixedDelayProps } from \"../types/fixedDelayProps\";\nimport { MAX_DELAY_MS, MS_MESSAGE, isValidDelay } from \"../utils/isValidDelay\";\n\nconst BREAK_AT_MESSAGE = `breakAt must be a positive number if defined (at most ${MAX_DELAY_MS})`;\n\n/**\n * Wait `ms` milliseconds, or `breakAt` milliseconds if that is shorter, or\n * until `cancel` is called.\n *\n * Invalid input throws on the call, never through the promise: a `TypeError`\n * for a value of the wrong type and a `RangeError` for a value of the right\n * type that is not allowed.\n *\n * @param {FixedDelayProps} props { ms, breakAt } with returnElapsed omitted or false\n *\n * @returns {object} An object containing the promise, which resolves with\n * undefined when the delay ends, and a cancel function that ends it\n * immediately.\n *\n * @throws {TypeError} props must be an object\n * @throws {TypeError | RangeError} ms must be a positive number (at most 2147483647)\n * @throws {TypeError | RangeError} breakAt must be a positive number if defined (at most 2147483647)\n * @throws {TypeError} returnElapsed must be a boolean if defined\n */\nexport function fixedDelay(props: FixedDelayProps & { returnElapsed?: false }): {\n promise: Promise<void>;\n cancel: () => void;\n};\n/**\n * Wait `ms` milliseconds, or `breakAt` milliseconds if that is shorter, or\n * until `cancel` is called.\n *\n * Invalid input throws on the call, never through the promise: a `TypeError`\n * for a value of the wrong type and a `RangeError` for a value of the right\n * type that is not allowed.\n *\n * @param {FixedDelayProps} props { ms, breakAt } with returnElapsed: true\n *\n * @returns {object} An object containing the promise, which resolves with the\n * elapsed time in milliseconds when the delay ends, and a cancel function that\n * ends it immediately.\n *\n * @throws {TypeError} props must be an object\n * @throws {TypeError | RangeError} ms must be a positive number (at most 2147483647)\n * @throws {TypeError | RangeError} breakAt must be a positive number if defined (at most 2147483647)\n * @throws {TypeError} returnElapsed must be a boolean if defined\n */\nexport function fixedDelay(props: FixedDelayProps & { returnElapsed: true }): {\n promise: Promise<number>;\n cancel: () => void;\n};\n/**\n * Wait `ms` milliseconds, or `breakAt` milliseconds if that is shorter, or\n * until `cancel` is called.\n *\n * Invalid input throws on the call, never through the promise: a `TypeError`\n * for a value of the wrong type and a `RangeError` for a value of the right\n * type that is not allowed.\n *\n * @param {FixedDelayProps} props { ms, breakAt, returnElapsed }\n *\n * @returns {object} An object containing the promise, which resolves when the\n * delay ends with the elapsed time in milliseconds if returnElapsed is true\n * (undefined otherwise), and a cancel function that ends it immediately.\n *\n * @throws {TypeError} props must be an object\n * @throws {TypeError | RangeError} ms must be a positive number (at most 2147483647)\n * @throws {TypeError | RangeError} breakAt must be a positive number if defined (at most 2147483647)\n * @throws {TypeError} returnElapsed must be a boolean if defined\n */\nexport function fixedDelay(props: FixedDelayProps): {\n promise: Promise<number | void>;\n cancel: () => void;\n};\nexport function fixedDelay(props: FixedDelayProps): {\n promise: Promise<number | void>;\n cancel: () => void;\n} {\n // Validate props before reading it: destructuring null or undefined would\n // throw the engine's own TypeError, whose text differs between engines\n if (!isProps(props)) {\n throw new TypeError(PROPS_MESSAGE);\n }\n\n const { ms, breakAt, returnElapsed } = props;\n\n // Validate that ms is a positive number within the timer limit: a value of\n // the wrong type is a TypeError, a number out of range a RangeError\n if (!isValidDelay(ms)) {\n throw typeof ms === \"number\"\n ? new RangeError(MS_MESSAGE)\n : new TypeError(MS_MESSAGE);\n }\n\n // Validate that breakAt is a positive number within the timer limit if\n // defined (undefined means omitted; null is a value of the wrong type)\n if (breakAt !== undefined && !isValidDelay(breakAt)) {\n throw typeof breakAt === \"number\"\n ? new RangeError(BREAK_AT_MESSAGE)\n : new TypeError(BREAK_AT_MESSAGE);\n }\n\n // Validate that returnElapsed is a boolean if defined\n if (returnElapsed !== undefined && typeof returnElapsed !== \"boolean\") {\n throw new TypeError(\"returnElapsed must be a boolean if defined\");\n }\n\n const startTime = Date.now();\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let breakTimeoutId: ReturnType<typeof setTimeout> | undefined;\n let finish!: () => void;\n\n const promise = new Promise<number | void>((resolve) => {\n // Clear every pending timer (so none keeps the process alive) and resolve.\n // Calling it more than once is harmless: a promise only resolves once.\n finish = () => {\n clearTimeout(timeoutId);\n clearTimeout(breakTimeoutId);\n resolve(returnElapsed ? Date.now() - startTime : undefined);\n };\n });\n\n timeoutId = setTimeout(finish, ms);\n\n if (breakAt !== undefined) {\n breakTimeoutId = setTimeout(finish, breakAt);\n }\n\n // Return the promise and a cancel function\n return { promise, cancel: finish };\n}\n","/**\n * Check whether a value is a promise or another thenable (an object with a\n * `then` method), such as the result of an async function.\n */\nexport function isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n value != null && typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n","import { PROPS_MESSAGE, isProps } from \"../../utils/isProps\";\nimport type { FixedRepeaterProps } from \"../types/fixedRepeaterProps\";\nimport { isPromiseLike } from \"../utils/isPromiseLike\";\nimport { MS_MESSAGE, isValidDelay } from \"../utils/isValidDelay\";\n\nconst TIMES_MESSAGE = `times must be a positive integer (at most ${Number.MAX_SAFE_INTEGER})`;\n\n/**\n * Call a function a fixed number of times at a fixed interval, without\n * overlapping calls.\n *\n * The first call happens `ms` after `fixedRepeater` is called, and each\n * following call starts `ms` after the previous one started. A call that takes\n * longer than `ms` delays the next one, which then starts as soon as it\n * finishes. If the callback returns a promise or another thenable (an object\n * with a `then` method), the call finishes when that promise settles, so calls\n * never overlap. If a callback promise never settles, the repeater waits\n * forever; call `cancel` to stop it.\n *\n * Invalid input throws on the call, never through the promise: a `TypeError`\n * for a value of the wrong type and a `RangeError` for a value of the right\n * type that is not allowed.\n *\n * @param {FixedRepeaterProps} props { callback, ms, times }\n *\n * @returns {object} An object containing the promise and a cancel function.\n * The promise resolves with the number of calls made once the last call has\n * finished (including its promise). If the callback throws or its promise\n * rejects, the repetitions stop and the promise rejects with that error.\n * `cancel` stops the repetitions and resolves the promise right away with the\n * number of calls made so far, counting a call still in progress. Nothing that\n * call does afterwards changes the result: a promise it returned is not\n * awaited and is ignored even if it rejects, and an error it throws after\n * calling `cancel` is ignored.\n *\n * @throws {TypeError} props must be an object\n * @throws {TypeError} callback must be a function\n * @throws {TypeError | RangeError} ms must be a positive number (at most 2147483647)\n * @throws {TypeError | RangeError} times must be a positive integer (at most 9007199254740991)\n */\nexport function fixedRepeater(props: FixedRepeaterProps): {\n promise: Promise<number>;\n cancel: () => void;\n} {\n // Validate props before reading it: destructuring null or undefined would\n // throw the engine's own TypeError, whose text differs between engines.\n // A function passed in place of the props is rejected here too.\n if (!isProps(props)) {\n throw new TypeError(PROPS_MESSAGE);\n }\n\n const { callback, ms, times } = props;\n\n // Validate that callback is a function\n if (typeof callback !== \"function\") {\n throw new TypeError(\"callback must be a function\");\n }\n\n // Validate that ms is a positive number within the timer limit: a value of\n // the wrong type is a TypeError, a number out of range a RangeError\n if (!isValidDelay(ms)) {\n throw typeof ms === \"number\"\n ? new RangeError(MS_MESSAGE)\n : new TypeError(MS_MESSAGE);\n }\n\n // Validate that times is a positive safe integer: a value of the wrong type\n // is a TypeError, any other number a RangeError. The call counter stops\n // growing at 2^53 (2^53 + 1 rounds back to 2^53), so a larger times would\n // never be reached and the repeater would never resolve on its own. The\n // limit is MAX_SAFE_INTEGER, the same bound randomInt uses.\n if (!Number.isSafeInteger(times) || times <= 0) {\n throw typeof times === \"number\"\n ? new RangeError(TIMES_MESSAGE)\n : new TypeError(TIMES_MESSAGE);\n }\n\n let count = 0;\n let settled = false;\n let startedAt = 0;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let resolvePromise!: (count: number) => void;\n let rejectPromise!: (reason: unknown) => void;\n\n const promise = new Promise<number>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n\n // Settle the promise once; later calls (after cancel, for example) do nothing\n const settle = (outcome: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timeoutId);\n outcome();\n };\n\n const fail = (error: unknown) => settle(() => rejectPromise(error));\n\n // Called once the current call has finished, including its promise\n const next = () => {\n if (settled) return;\n if (count >= times) {\n settle(() => resolvePromise(count));\n return;\n }\n\n // Start the next call ms after the current one started (the setInterval\n // rhythm), or right away if the current one took longer than ms.\n // The measured time is clamped to [0, ms]: a system clock that jumps can\n // shorten or stretch one wait, never beyond 0 or ms, and the delay is\n // never negative. A wait of 0 still goes through setTimeout, because\n // calling run() directly would recurse synchronously and block the\n // event loop until the last call.\n const elapsed = Math.min(Math.max(Date.now() - startedAt, 0), ms);\n timeoutId = setTimeout(run, ms - elapsed);\n };\n\n const run = () => {\n count++;\n startedAt = Date.now();\n\n // Reading `then` can throw too (a getter, a revoked Proxy), so the\n // thenable check stays inside the try, together with the call\n let pending: PromiseLike<unknown> | undefined;\n try {\n const result = callback();\n if (isPromiseLike(result)) pending = result;\n } catch (error) {\n fail(error);\n return;\n }\n\n if (pending) {\n // Promise.resolve adopts any thenable safely: it settles only once,\n // even if the thenable calls back twice or throws from then\n Promise.resolve(pending).then(next, fail);\n } else {\n next();\n }\n };\n\n timeoutId = setTimeout(run, ms);\n\n // Return the promise and a cancel function\n return {\n promise,\n cancel: () => settle(() => resolvePromise(count)),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,gBAAgB;AAQtB,SAAS,QAAQ,OAAiC;AACvD,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;ACXA,IAAM,aAAa,KAAK;AACxB,IAAM,aAAa,KAAK;AACxB,IAAM,aAAa,KAAK;AAMxB,IAAM,eAAe;AAWd,SAAS,YAAY,GAAmB;AAK7C,MAAI,KAAK,WAAY,QAAO,KAAK,MAAM,KAAK,OAAO,IAAI,CAAC;AAQxD,QAAM,QAAQ,aAAc,aAAa;AACzC,MAAI,QAAQ;AAEZ,WAAS,UAAU,GAAG,UAAU,cAAc,WAAW;AACvD,YACE,KAAK,MAAM,KAAK,OAAO,IAAI,UAAU,IAAI,aACzC,KAAK,MAAM,KAAK,OAAO,IAAI,UAAU;AACvC,QAAI,QAAQ,MAAO;AAAA,EACrB;AAKA,SAAO,QAAQ;AACjB;;;AC1CA,IAAM,cAAc;AACpB,IAAM,cAAc;AACpB,IAAM,WAAW,OAAO;AACxB,IAAM,aAAa,WAAW,CAAC,QAAQ,QAAQ,QAAQ;AA8BhD,SAAS,UAAU,QAAwB,CAAC,GAAW;AAG5D,MAAI,CAAC,QAAQ,KAAK,GAAG;AACnB,UAAM,IAAI,UAAU,GAAG,aAAa,aAAa;AAAA,EACnD;AAGA,QAAM,EAAE,KAAK,UAAU,KAAK,SAAS,IAAI;AACzC,QAAM,MAAM,aAAa,SAAY,cAAc;AACnD,QAAM,MAAM,aAAa,SAAY,cAAc;AAInD,MAAI,CAAC,OAAO,cAAc,GAAG,GAAG;AAC9B,UAAM,UAAU,+BAA+B,UAAU;AACzD,UAA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