@thainanluiz/tssuper 0.0.11 → 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/README.md CHANGED
@@ -1,37 +1,130 @@
1
- # TSSUPER
2
-
3
- ## Simple add-on for TypeScript
4
-
5
- ![TSSuper logo](https://github.com/thainanluiz/TSSuper/blob/main/assets/logo/tssuper259x259.png "Logo TSSuper")
6
-
7
- <br>
8
- How to install
9
-
10
- ```shell
11
- npm i @thainanluiz/tssuper
12
- ```
13
-
14
- Package available [here] | current stable version [0.0.11] | current version [0.0.11]
15
-
16
- <br>
17
-
18
- How to use
19
-
20
- ```ts
21
- const { math } = require("@thainanluiz/tssuper");
22
- const { delay } = require("@thainanluiz/tssuper");
23
- ```
24
-
25
- <br>
26
-
27
- See [functions] to get available functions <br>
28
- See [examples] folder <br>
29
- The entire [changelog here] <br>
30
-
31
- [here]: https://www.npmjs.com/package/@thainanluiz/tssuper
32
- [1.0.0]: https://www.npmjs.com/package/@thainanluiz/tssuper/v/1.0.0
33
- [0.0.11]: https://www.npmjs.com/package/@thainanluiz/tssuper/v/0.0.11
34
- [functions]: https://github.com/thainanluiz/TSSuper/blob/main/FUNCTIONS.md
35
- [examples]: https://github.com/thainanluiz/TSSuper/blob/main/examples/
36
- [changelog here]: https://github.com/thainanluiz/TSSuper/blob/main/CHANGELOG.md
37
- [TSSuper]: https://github.com/thainanluiz/TSSuper
1
+ # TSSuper
2
+
3
+ ![TSSuper logo](https://raw.githubusercontent.com/thainanluiz/TSSuper/main/assets/logo/tssuper259x259.png "TSSuper logo")
4
+
5
+ [![npm](https://img.shields.io/npm/v/@thainanluiz/tssuper)](https://www.npmjs.com/package/@thainanluiz/tssuper)
6
+ [![CI](https://github.com/thainanluiz/TSSuper/actions/workflows/test.yml/badge.svg)](https://github.com/thainanluiz/TSSuper/actions/workflows/test.yml)
7
+ [![License: MIT](https://img.shields.io/github/license/thainanluiz/TSSuper)](https://github.com/thainanluiz/TSSuper/blob/main/LICENSE)
8
+ [![Types included](https://img.shields.io/npm/types/@thainanluiz/tssuper)](https://github.com/thainanluiz/TSSuper/blob/main/FUNCTIONS.md)
9
+ [![Zero dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)](https://github.com/thainanluiz/TSSuper/blob/main/package.json)
10
+
11
+ Small, typed utilities for TypeScript and JavaScript: random integers, rounding, delays and repeated tasks.
12
+
13
+ - **Zero runtime dependencies.** Installing TSSuper adds nothing else to your project.
14
+ - **Written in TypeScript.** Type declarations are included, for both ES modules and CommonJS.
15
+ - **Strict about input.** Every function validates its argument and throws a `TypeError` or `RangeError` with a clear, documented message, instead of returning a wrong result.
16
+ - **Portable by design.** The code uses only the ECMAScript 2020 standard library and timers, with no Node.js or browser APIs. See [Runtime support](#runtime-support) for what is verified.
17
+ - **Cancellable timers.** The delay functions return a promise and a `cancel` function, and the repeater waits for async callbacks.
18
+
19
+ > Upgrading from 0.0.12? Version 0.1.0 has breaking changes. See the [migration guide](https://github.com/thainanluiz/TSSuper/blob/main/docs/migration/0.1.0.md).
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ npm install @thainanluiz/tssuper
25
+ ```
26
+
27
+ ```sh
28
+ pnpm add @thainanluiz/tssuper
29
+ ```
30
+
31
+ ```sh
32
+ yarn add @thainanluiz/tssuper
33
+ ```
34
+
35
+ ```sh
36
+ bun add @thainanluiz/tssuper
37
+ ```
38
+
39
+ ```sh
40
+ deno add npm:@thainanluiz/tssuper
41
+ ```
42
+
43
+ ## Quick start
44
+
45
+ ```ts
46
+ import { math, delay } from "@thainanluiz/tssuper";
47
+
48
+ // A random integer from 1 to 6, both inclusive
49
+ console.log(math.randomInt({ min: 1, max: 6 })); // for example 4
50
+
51
+ // Round to 2 decimal places, halves away from zero
52
+ console.log(math.formatNumber({ number: 1.005, decimalPlaces: 2 })); // 1.01
53
+
54
+ // Wait half a second
55
+ await delay.fixedDelay({ ms: 500 }).promise;
56
+
57
+ // Call a function 3 times, once every second. An async callback is awaited
58
+ // before the next call, so calls never overlap.
59
+ const count = await delay.fixedRepeater({
60
+ callback: async () => console.log("tick"),
61
+ ms: 1000,
62
+ times: 3,
63
+ }).promise;
64
+ console.log(count); // 3
65
+
66
+ // Invalid input throws right away, with the cause in the class and the message
67
+ try {
68
+ delay.fixedDelay({ ms: -1 });
69
+ } catch (error) {
70
+ console.log(error instanceof RangeError); // true
71
+ console.log((error as Error).message); // ms must be a positive number (at most 2147483647)
72
+ }
73
+ ```
74
+
75
+ With CommonJS:
76
+
77
+ ```js
78
+ const { math, delay } = require("@thainanluiz/tssuper");
79
+ ```
80
+
81
+ More runnable examples are in the [`examples`](https://github.com/thainanluiz/TSSuper/tree/main/examples) folder.
82
+
83
+ ## API
84
+
85
+ Each function takes a single object argument. The [API reference](https://github.com/thainanluiz/TSSuper/blob/main/FUNCTIONS.md) documents every parameter, limit, error message and edge case.
86
+
87
+ ### `math`
88
+
89
+ | Function | What it does |
90
+ | --- | --- |
91
+ | [`randomInt({ min?, max? })`](https://github.com/thainanluiz/TSSuper/blob/main/FUNCTIONS.md#mathrandomint) | Returns a random integer from `min` to `max`, both inclusive (0 to 10 by default). It uses `Math.random()`, so it is not for passwords, tokens or keys. |
92
+ | [`formatNumber({ number, decimalPlaces })`](https://github.com/thainanluiz/TSSuper/blob/main/FUNCTIONS.md#mathformatnumber) | Rounds a number to a number of decimal places, halves away from zero, so `1.005` becomes `1.01`. |
93
+
94
+ ### `delay`
95
+
96
+ | Function | What it does |
97
+ | --- | --- |
98
+ | [`fixedDelay({ ms, breakAt?, returnElapsed? })`](https://github.com/thainanluiz/TSSuper/blob/main/FUNCTIONS.md#delayfixeddelay) | Waits `ms` milliseconds, or less with `breakAt` or `cancel()`. Returns `{ promise, cancel }`; the promise can resolve with the elapsed time. |
99
+ | [`fixedRepeater({ callback, ms, times })`](https://github.com/thainanluiz/TSSuper/blob/main/FUNCTIONS.md#delayfixedrepeater) | Calls `callback` `times` times, one call every `ms` milliseconds, waiting for async callbacks so calls never overlap. Returns `{ promise, cancel }`; the promise resolves with the number of calls made. |
100
+
101
+ The props types are exported too: `math.RandomIntProps`, `math.FormatNumberProps`, `delay.FixedDelayProps` and `delay.FixedRepeaterProps`.
102
+
103
+ ## Runtime support
104
+
105
+ | Runtime | Status |
106
+ | --- | --- |
107
+ | Node.js 22, 24 and 26 | **Verified.** CI runs the type check, the tests and the package checks on each version. |
108
+ | Bun, Deno and browsers | **Designed for, not yet verified.** CI does not run on them yet; [verifying them is planned](https://github.com/thainanluiz/TSSuper/issues/36). |
109
+
110
+ "Designed for" means:
111
+
112
+ - The source uses only the ECMAScript 2020 standard library and the `setTimeout`, `clearTimeout`, `setInterval` and `clearInterval` timers. The type check fails if the source uses an API outside that set, such as `process`, `Buffer` or `window`.
113
+ - The package ships an ES module build and a CommonJS build, both compiled for ES2020, with type declarations for each, and is marked as free of side effects for tree shaking.
114
+
115
+ Older Node.js versions may work, but they are not tested.
116
+
117
+ ## Documentation
118
+
119
+ - [API reference](https://github.com/thainanluiz/TSSuper/blob/main/FUNCTIONS.md)
120
+ - [Examples](https://github.com/thainanluiz/TSSuper/tree/main/examples)
121
+ - [Changelog](https://github.com/thainanluiz/TSSuper/blob/main/CHANGELOG.md)
122
+ - [Migration guide from 0.0.12 to 0.1.0](https://github.com/thainanluiz/TSSuper/blob/main/docs/migration/0.1.0.md)
123
+ - [Versioning policy](https://github.com/thainanluiz/TSSuper/blob/main/docs/versioning.md): while the version is below 1.0.0, a breaking change bumps the minor version.
124
+ - [Contributing](https://github.com/thainanluiz/TSSuper/blob/main/CONTRIBUTING.md)
125
+
126
+ ## License
127
+
128
+ Released under the [MIT License](https://github.com/thainanluiz/TSSuper/blob/main/LICENSE). Copyright (c) 2024 Thainan Luiz.
129
+
130
+ Versions 0.0.12 and earlier were published under GPL-3.0-only.
package/dist/index.d.mts CHANGED
@@ -1,35 +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 integers
14
- * @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
15
42
  */
16
- declare function randomInt({ min, max }: RandomIntProps): number;
43
+ declare function randomInt(props?: RandomIntProps): number;
17
44
 
18
45
  type FormatNumberProps = {
46
+ /** The number to be formatted. Must be finite. */
19
47
  number: number;
48
+ /** Number of decimal places to round to (integer from 0 to 100). */
20
49
  decimalPlaces: number;
21
50
  };
22
51
 
23
52
  /**
24
- * Format a number to a specific number of decimal places
25
- * @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.
56
+ *
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.
26
59
  *
27
- * @returns {number}
60
+ * @param {FormatNumberProps} props { number, decimalPlaces }
28
61
  *
29
- * @throws {Error} number must be a number
30
- * @throws {Error} decimalPlaces must be an integer
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
31
70
  */
32
- declare function formatNumber({ number, decimalPlaces, }: FormatNumberProps): number;
71
+ declare function formatNumber(props: FormatNumberProps): number;
33
72
 
34
73
  type index$1_FormatNumberProps = FormatNumberProps;
35
74
  type index$1_RandomIntProps = RandomIntProps;
@@ -40,30 +79,156 @@ declare namespace index$1 {
40
79
  }
41
80
 
42
81
  type FixedDelayProps = {
82
+ /** Delay in milliseconds (positive, at most 2147483647). */
43
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
+ */
44
88
  breakAt?: number;
89
+ /** If true, the promise resolves with the elapsed time in milliseconds. */
45
90
  returnElapsed?: boolean;
46
91
  };
47
92
 
48
93
  /**
49
- * Create a fixed delay function that returns a promise that resolves after a given number of milliseconds.
50
- * @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
51
102
  *
52
- * @returns {object} An object containing the promise and a cancel function
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.
53
106
  *
54
- * @throws {Error} ms must be a positive number
55
- * @throws {Error} breakAt must be a positive number if defined
56
- * @throws {Error} returnElapsed must be a boolean if defined
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
57
111
  */
58
- declare function fixedDelay({ ms, breakAt, returnElapsed }: FixedDelayProps): {
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.
121
+ *
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.
125
+ *
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
161
+ */
162
+ declare function fixedDelay(props: FixedDelayProps): {
59
163
  promise: Promise<number | void>;
60
164
  cancel: () => void;
61
165
  };
62
166
 
167
+ type FixedRepeaterProps = {
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
+ */
183
+ ms: number;
184
+ /** Number of times the callback is called (positive integer, at most 9007199254740991). */
185
+ times: number;
186
+ };
187
+
188
+ /**
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.
199
+ *
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.
203
+ *
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)
220
+ */
221
+ declare function fixedRepeater(props: FixedRepeaterProps): {
222
+ promise: Promise<number>;
223
+ cancel: () => void;
224
+ };
225
+
63
226
  type index_FixedDelayProps = FixedDelayProps;
227
+ type index_FixedRepeaterProps = FixedRepeaterProps;
64
228
  declare const index_fixedDelay: typeof fixedDelay;
229
+ declare const index_fixedRepeater: typeof fixedRepeater;
65
230
  declare namespace index {
66
- export { type index_FixedDelayProps as FixedDelayProps, index_fixedDelay as fixedDelay };
231
+ export { type index_FixedDelayProps as FixedDelayProps, type index_FixedRepeaterProps as FixedRepeaterProps, index_fixedDelay as fixedDelay, index_fixedRepeater as fixedRepeater };
67
232
  }
68
233
 
69
234
  export { index as delay, index$1 as math };