@inglorious/utils 5.2.0 → 5.3.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
@@ -133,6 +133,20 @@ writeJSON("high-scores", [...scores, 1200]) // => true
133
133
 
134
134
  Pass another `Storage` as the last argument, such as `sessionStorage` or a fake in tests.
135
135
 
136
+ ### Using promises as they settle
137
+
138
+ Start several requests at once and use each answer as soon as it arrives, such as
139
+ streaming two model replies to a client. The first rejection is thrown, and the promises
140
+ still pending never end up as unhandled rejections.
141
+
142
+ ```javascript
143
+ import { asSettled } from "@inglorious/utils/promise.js"
144
+
145
+ for await (const reply of asSettled([askSunny(), askCrowley()])) {
146
+ send(reply) // fastest first
147
+ }
148
+ ```
149
+
136
150
  ---
137
151
 
138
152
  ## API
@@ -154,8 +168,9 @@ know whether a helper lives under `data-structures` or `math`:
154
168
  - **`@inglorious/utils/quaternion`**: `quaternion` and `combine`.
155
169
  - **`@inglorious/utils/vector`**: Single-vector helpers (`magnitude`, `normalize`, `rotate`, ...) alongside multi-vector helpers (`cross`, `dot`, `sum`, ...).
156
170
 
157
- One module stands on its own:
171
+ Two modules stand on their own:
158
172
 
173
+ - **`@inglorious/utils/promise`**: `asSettled`, for using promises in the order they settle.
159
174
  - **`@inglorious/utils/storage`**: `readJSON` and `writeJSON`, for keeping JSON in `localStorage`.
160
175
 
161
176
  `divide`, `mod`, `multiply` and `power` accept either a scalar or one or more vectors:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/utils",
3
- "version": "5.2.0",
3
+ "version": "5.3.0",
4
4
  "description": "A set of general-purpose utility functions designed with functional programming principles in mind.",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -102,6 +102,14 @@
102
102
  "types": "./types/data-structures/object.d.ts",
103
103
  "import": "./src/data-structures/object.js"
104
104
  },
105
+ "./promise.js": {
106
+ "types": "./types/data-structures/promise.d.ts",
107
+ "import": "./src/data-structures/promise.js"
108
+ },
109
+ "./promise": {
110
+ "types": "./types/promise.d.ts",
111
+ "import": "./src/promise.js"
112
+ },
105
113
  "./quaternion.js": {
106
114
  "types": "./types/math/quaternion.d.ts",
107
115
  "import": "./src/math/quaternion.js"
@@ -9,6 +9,7 @@ const DEFAULT_COMPARATOR = (a, b) => b - a
9
9
 
10
10
  const LESS_THAN_ZERO = 0
11
11
  const GREATER_THAN_ZERO = 0
12
+ const NONE = 0
12
13
 
13
14
  /**
14
15
  * Checks if an array contains a specific item.
@@ -53,6 +54,17 @@ export function isArray(value) {
53
54
  return Array.isArray(value)
54
55
  }
55
56
 
57
+ /**
58
+ * Keeps only the last items of an array, in an immutable way, such as the most recent entries of a log.
59
+ *
60
+ * @param {Array} arr - The array to trim.
61
+ * @param {number} count - How many items to keep from the end.
62
+ * @returns {Array} - A new array with at most `count` items, the last ones of `arr`.
63
+ */
64
+ export function keepLast(arr, count) {
65
+ return count > NONE ? arr.slice(-count) : []
66
+ }
67
+
56
68
  /**
57
69
  * Finds the maximum item in an array based on a comparator function.
58
70
  *
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Yields the results of some promises in the order they settle, not the order given,
3
+ * so each can be used as soon as it is ready.
4
+ *
5
+ * The first rejection is thrown. Every promise is settled first, so the ones still
6
+ * pending never end up as unhandled rejections, even when several fail or the caller
7
+ * stops iterating early.
8
+ *
9
+ * @template T
10
+ * @param {Iterable<T | PromiseLike<T>>} promises - The promises to wait for. Plain values count as already fulfilled.
11
+ * @returns {AsyncGenerator<T>} The fulfilled values, fastest first.
12
+ */
13
+ export async function* asSettled(promises) {
14
+ const pending = new Map(
15
+ Array.from(promises, (promise, index) => [
16
+ index,
17
+ Promise.resolve(promise).then(
18
+ (value) => ({ index, isFulfilled: true, value }),
19
+ (reason) => ({ index, isFulfilled: false, reason }),
20
+ ),
21
+ ]),
22
+ )
23
+
24
+ while (pending.size) {
25
+ const { index, isFulfilled, value, reason } = await Promise.race(
26
+ pending.values(),
27
+ )
28
+ pending.delete(index)
29
+ if (!isFulfilled) {
30
+ throw reason
31
+ }
32
+ yield value
33
+ }
34
+ }
@@ -20,6 +20,11 @@ export function ensureArray<T>(value: T): T extends readonly unknown[] ? T : T[]
20
20
  */
21
21
  export function isArray(value: unknown): value is readonly unknown[]
22
22
 
23
+ /**
24
+ * Keeps only the last `count` items of an array, immutably.
25
+ */
26
+ export function keepLast<T>(arr: readonly T[], count: number): T[]
27
+
23
28
  /**
24
29
  * Finds the maximum item in an array using a comparator.
25
30
  */
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Yields the results of some promises in the order they settle, not the order
3
+ * given. The first rejection is thrown, and the promises still pending never
4
+ * end up as unhandled rejections.
5
+ *
6
+ * @param promises - The promises to wait for. Plain values count as already fulfilled.
7
+ * @returns The fulfilled values, fastest first.
8
+ */
9
+ export function asSettled<T>(
10
+ promises: Iterable<T | PromiseLike<T>>,
11
+ ): AsyncGenerator<Awaited<T>>