@inglorious/utils 5.2.0 → 5.4.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
@@ -131,7 +131,23 @@ const scores = readJSON("high-scores", [])
131
131
  writeJSON("high-scores", [...scores, 1200]) // => true
132
132
  ```
133
133
 
134
- Pass another `Storage` as the last argument, such as `sessionStorage` or a fake in tests.
134
+ Pass another `Storage` as the last argument, such as `sessionStorage` or a fake in tests, or a function giving one: a function giving nothing means no storage.
135
+
136
+ `readItem` and `writeItem` do the same for plain strings, and also take a storage answering with promises, such as Capacitor Preferences: `readItem` then gives its promise back. `parseJSON(raw, fallback)` parses what was read.
137
+
138
+ ### Using promises as they settle
139
+
140
+ Start several requests at once and use each answer as soon as it arrives, such as
141
+ streaming two model replies to a client. The first rejection is thrown, and the promises
142
+ still pending never end up as unhandled rejections.
143
+
144
+ ```javascript
145
+ import { asSettled } from "@inglorious/utils/promise.js"
146
+
147
+ for await (const reply of asSettled([askSunny(), askCrowley()])) {
148
+ send(reply) // fastest first
149
+ }
150
+ ```
135
151
 
136
152
  ---
137
153
 
@@ -150,13 +166,14 @@ The four largest modules are also available as top-level subpaths, so you don't
150
166
  know whether a helper lives under `data-structures` or `math`:
151
167
 
152
168
  - **`@inglorious/utils/functions`**: `compose`, `debounce`, `isFunction`, `pipe`, `throttle`.
153
- - **`@inglorious/utils/object`**: Single-object helpers (`clone`, `get`, `set`, `produce`, ...) alongside multi-object helpers (`merge`, `extend`, `defaults`, ...).
169
+ - **`@inglorious/utils/object`**: Single-object helpers (`clone`, `get`, `pick`, `set`, `produce`, ...) alongside multi-object helpers (`merge`, `extend`, `defaults`, ...).
154
170
  - **`@inglorious/utils/quaternion`**: `quaternion` and `combine`.
155
171
  - **`@inglorious/utils/vector`**: Single-vector helpers (`magnitude`, `normalize`, `rotate`, ...) alongside multi-vector helpers (`cross`, `dot`, `sum`, ...).
156
172
 
157
- One module stands on its own:
173
+ Two modules stand on their own:
158
174
 
159
- - **`@inglorious/utils/storage`**: `readJSON` and `writeJSON`, for keeping JSON in `localStorage`.
175
+ - **`@inglorious/utils/promise`**: `asSettled`, for using promises in the order they settle, and `isPromiseLike`.
176
+ - **`@inglorious/utils/storage`**: `readJSON` and `writeJSON`, for keeping JSON in `localStorage`, and `readItem`, `writeItem` and `parseJSON` underneath them.
160
177
 
161
178
  `divide`, `mod`, `multiply` and `power` accept either a scalar or one or more vectors:
162
179
  a scalar is applied to every component, while vectors are combined component-wise.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/utils",
3
- "version": "5.2.0",
3
+ "version": "5.4.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/data-structures/promise.d.ts",
111
+ "import": "./src/data-structures/promise.js"
112
+ },
105
113
  "./quaternion.js": {
106
114
  "types": "./types/math/quaternion.d.ts",
107
115
  "import": "./src/math/quaternion.js"
@@ -146,9 +154,9 @@
146
154
  "sideEffects": false,
147
155
  "devDependencies": {
148
156
  "@inglorious/eslint-config": "1.2.0",
149
- "prettier": "^3.9.6",
150
- "vite": "^8.2.2",
151
- "vitest": "^5.0.0"
157
+ "prettier": "^3.9.10",
158
+ "vite": "^8.3.8",
159
+ "vitest": "^5.1.0"
152
160
  },
153
161
  "engines": {
154
162
  "node": ">= 26"
@@ -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
  *
@@ -316,6 +316,22 @@ export function mergeWith(merger, target, ...sources) {
316
316
  .reduce((acc, source) => deepMerge(acc, source, merger), target)
317
317
  }
318
318
 
319
+ /**
320
+ * A new object with only the given keys that the source has.
321
+ *
322
+ * @param {Object | null | undefined} source - The object to pick from.
323
+ * @param {string[]} keys - The keys to keep.
324
+ * @returns {Object} The picked properties.
325
+ */
326
+ export function pick(source, keys) {
327
+ const picked = {}
328
+ if (source == null) return picked
329
+ for (const key of keys) {
330
+ if (key in source) picked[key] = source[key]
331
+ }
332
+ return picked
333
+ }
334
+
319
335
  /**
320
336
  * A utility function inspired by Immer's `produce` API. It provides a convenient
321
337
  * way to work with immutable data structures by allowing "mutations" on a
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Whether a value can be awaited like a promise: anything with a `then` method.
3
+ *
4
+ * @param {*} value - The value to check.
5
+ * @returns {boolean} `true` for a promise or thenable.
6
+ */
7
+ export function isPromiseLike(value) {
8
+ return typeof value?.then === "function"
9
+ }
10
+
11
+ /**
12
+ * Yields the results of some promises in the order they settle, not the order given,
13
+ * so each can be used as soon as it is ready.
14
+ *
15
+ * The first rejection is thrown. Every promise is settled first, so the ones still
16
+ * pending never end up as unhandled rejections, even when several fail or the caller
17
+ * stops iterating early.
18
+ *
19
+ * @template T
20
+ * @param {Iterable<T | PromiseLike<T>>} promises - The promises to wait for. Plain values count as already fulfilled.
21
+ * @returns {AsyncGenerator<T>} The fulfilled values, fastest first.
22
+ */
23
+ export async function* asSettled(promises) {
24
+ const pending = new Map(
25
+ Array.from(promises, (promise, index) => [
26
+ index,
27
+ Promise.resolve(promise).then(
28
+ (value) => ({ index, isFulfilled: true, value }),
29
+ (reason) => ({ index, isFulfilled: false, reason }),
30
+ ),
31
+ ]),
32
+ )
33
+
34
+ while (pending.size) {
35
+ const { index, isFulfilled, value, reason } = await Promise.race(
36
+ pending.values(),
37
+ )
38
+ pending.delete(index)
39
+ if (!isFulfilled) {
40
+ throw reason
41
+ }
42
+ yield value
43
+ }
44
+ }
package/src/storage.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { isPromiseLike } from "./data-structures/promise.js"
2
+
1
3
  const DEFAULT_STORAGE = () => globalThis.localStorage
2
4
 
3
5
  /**
@@ -11,17 +13,11 @@ const DEFAULT_STORAGE = () => globalThis.localStorage
11
13
  *
12
14
  * @param {string} key - Where the value is kept.
13
15
  * @param {*} fallback - What to answer when there is nothing usable to read.
14
- * @param {Storage} [storage] - Where to read from. Defaults to the browser's own.
16
+ * @param {Storage | (() => Storage | undefined)} [storage] - Where to read from. Defaults to the browser's own.
15
17
  * @returns {*} The stored value, or the fallback.
16
18
  */
17
19
  export function readJSON(key, fallback, storage) {
18
- try {
19
- const raw = store(storage)?.getItem(key)
20
- if (raw === null || raw === undefined) return fallback
21
- return JSON.parse(raw)
22
- } catch {
23
- return fallback
24
- }
20
+ return parseJSON(readItem(key, storage), fallback)
25
21
  }
26
22
 
27
23
  /**
@@ -33,20 +29,73 @@ export function readJSON(key, fallback, storage) {
33
29
  *
34
30
  * @param {string} key - Where to keep the value.
35
31
  * @param {*} value - The value to keep.
36
- * @param {Storage} [storage] - Where to write to. Defaults to the browser's own.
32
+ * @param {Storage | (() => Storage | undefined)} [storage] - Where to write to. Defaults to the browser's own.
37
33
  * @returns {boolean} `true` if the value was written.
38
34
  */
39
35
  export function writeJSON(key, value, storage) {
40
36
  try {
41
- const target = store(storage)
37
+ return writeItem(key, JSON.stringify(value), storage)
38
+ } catch {
39
+ return false
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Parses what storage held, or answers the fallback when it held nothing or
45
+ * nothing that parses.
46
+ *
47
+ * @param {string | null | undefined} raw - What was read.
48
+ * @param {*} [fallback=null] - What to answer otherwise.
49
+ * @returns {*} The parsed value, or the fallback.
50
+ */
51
+ export function parseJSON(raw, fallback = null) {
52
+ if (raw === null || raw === undefined) return fallback
53
+ try {
54
+ return JSON.parse(raw)
55
+ } catch {
56
+ return fallback
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Reads a string without throwing: absent or refusing storage reads as `null`.
62
+ * A storage answering with promises, such as Capacitor Preferences, gives its
63
+ * promise back.
64
+ *
65
+ * @param {string} key - Where the value is kept.
66
+ * @param {Storage | (() => Storage | undefined)} [storage] - Where to read from, or a function giving it: one giving nothing means no storage. Defaults to the browser's own.
67
+ * @returns {string | null | Promise<string | null>} The stored string.
68
+ */
69
+ export function readItem(key, storage) {
70
+ try {
71
+ return resolve(storage)?.getItem(key) ?? null
72
+ } catch {
73
+ return null
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Writes a string without throwing, and answers whether it was handed over. A
79
+ * storage answering with promises has its failures swallowed too.
80
+ *
81
+ * @param {string} key - Where to keep the value.
82
+ * @param {string} value - The value to keep.
83
+ * @param {Storage | (() => Storage | undefined)} [storage] - Where to write to, or a function giving it. Defaults to the browser's own.
84
+ * @returns {boolean} `true` if the storage took it.
85
+ */
86
+ export function writeItem(key, value, storage) {
87
+ try {
88
+ const target = resolve(storage)
42
89
  if (!target) return false
43
- target.setItem(key, JSON.stringify(value))
90
+ const written = target.setItem(key, value)
91
+ if (isPromiseLike(written)) written.then(undefined, () => {})
44
92
  return true
45
93
  } catch {
46
94
  return false
47
95
  }
48
96
  }
49
97
 
50
- function store(storage) {
98
+ function resolve(storage) {
99
+ if (typeof storage === "function") return storage()
51
100
  return storage ?? DEFAULT_STORAGE()
52
101
  }
@@ -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
  */
@@ -168,6 +168,16 @@ export function map<T extends object, R>(
168
168
  callback: (key: string, value: ObjectValue<T>, obj: T) => R,
169
169
  ): Record<string, R>
170
170
 
171
+ /** A new object with only the given keys that the source has. */
172
+ export function pick<T extends object, K extends keyof T & string>(
173
+ source: T | null | undefined,
174
+ keys: readonly K[],
175
+ ): Partial<Pick<T, K>>
176
+ export function pick(
177
+ source: object | null | undefined,
178
+ keys: readonly string[],
179
+ ): Record<string, unknown>
180
+
171
181
  /**
172
182
  * Merges source objects into a target in place.
173
183
  */
@@ -0,0 +1,14 @@
1
+ /** Whether a value can be awaited like a promise: anything with a `then` method. */
2
+ export function isPromiseLike(value: unknown): value is PromiseLike<unknown>
3
+
4
+ /**
5
+ * Yields the results of some promises in the order they settle, not the order
6
+ * given. The first rejection is thrown, and the promises still pending never
7
+ * end up as unhandled rejections.
8
+ *
9
+ * @param promises - The promises to wait for. Plain values count as already fulfilled.
10
+ * @returns The fulfilled values, fastest first.
11
+ */
12
+ export function asSettled<T>(
13
+ promises: Iterable<T | PromiseLike<T>>,
14
+ ): AsyncGenerator<Awaited<T>>
@@ -1,3 +1,16 @@
1
+ /** A storage, or a function giving one: a function giving nothing means no storage. */
2
+ export type StorageSource =
3
+ | Storage
4
+ | KeyValueStorage
5
+ | null
6
+ | (() => Storage | KeyValueStorage | undefined)
7
+
8
+ /** Anything that keeps strings like a Web Storage, now or with promises. */
9
+ export interface KeyValueStorage {
10
+ getItem(key: string): string | null | Promise<string | null>
11
+ setItem(key: string, value: string): void | Promise<void>
12
+ }
13
+
1
14
  /**
2
15
  * Reads a value back as JSON. Absent storage, a missing key or a value that
3
16
  * cannot be parsed all read as the fallback, rather than throwing.
@@ -10,7 +23,7 @@
10
23
  export function readJSON<T>(
11
24
  key: string,
12
25
  fallback: T,
13
- storage?: Storage | null,
26
+ storage?: StorageSource,
14
27
  ): T
15
28
 
16
29
  /**
@@ -25,5 +38,27 @@ export function readJSON<T>(
25
38
  export function writeJSON(
26
39
  key: string,
27
40
  value: unknown,
28
- storage?: Storage | null,
41
+ storage?: StorageSource,
42
+ ): boolean
43
+
44
+ /** Parses what storage held, or answers the fallback (`null` by default). */
45
+ export function parseJSON<T = unknown>(
46
+ raw: string | null | undefined,
47
+ fallback?: T,
48
+ ): T
49
+
50
+ /**
51
+ * Reads a string without throwing: absent or refusing storage reads as `null`.
52
+ * A storage answering with promises gives its promise back.
53
+ */
54
+ export function readItem(
55
+ key: string,
56
+ storage?: StorageSource,
57
+ ): string | null | Promise<string | null>
58
+
59
+ /** Writes a string without throwing, and answers whether the storage took it. */
60
+ export function writeItem(
61
+ key: string,
62
+ value: string,
63
+ storage?: StorageSource,
29
64
  ): boolean