@nlozgachev/pipelined 0.11.0 → 0.12.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.
@@ -0,0 +1,112 @@
1
+ export var Tuple;
2
+ (function (Tuple) {
3
+ /**
4
+ * Creates a pair from two values.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * Tuple.make("Paris", 2_161_000); // ["Paris", 2161000]
9
+ * ```
10
+ */
11
+ Tuple.make = (first, second) => [first, second];
12
+ /**
13
+ * Returns the first value from the pair.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * Tuple.first(Tuple.make("Paris", 2_161_000)); // "Paris"
18
+ * ```
19
+ */
20
+ Tuple.first = (tuple) => tuple[0];
21
+ /**
22
+ * Returns the second value from the pair.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * Tuple.second(Tuple.make("Paris", 2_161_000)); // 2161000
27
+ * ```
28
+ */
29
+ Tuple.second = (tuple) => tuple[1];
30
+ /**
31
+ * Transforms the first value, leaving the second unchanged.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * pipe(Tuple.make("alice", 42), Tuple.mapFirst((s) => s.toUpperCase())); // ["ALICE", 42]
36
+ * ```
37
+ */
38
+ Tuple.mapFirst = (f) => (tuple) => [f(tuple[0]), tuple[1]];
39
+ /**
40
+ * Transforms the second value, leaving the first unchanged.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * pipe(Tuple.make("alice", 42), Tuple.mapSecond((n) => n * 2)); // ["alice", 84]
45
+ * ```
46
+ */
47
+ Tuple.mapSecond = (f) => (tuple) => [tuple[0], f(tuple[1])];
48
+ /**
49
+ * Transforms both values independently in a single step.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * pipe(
54
+ * Tuple.make("alice", 42),
55
+ * Tuple.mapBoth(
56
+ * (name) => name.toUpperCase(),
57
+ * (score) => score * 2,
58
+ * ),
59
+ * ); // ["ALICE", 84]
60
+ * ```
61
+ */
62
+ Tuple.mapBoth = (onFirst, onSecond) => (tuple) => [
63
+ onFirst(tuple[0]),
64
+ onSecond(tuple[1]),
65
+ ];
66
+ /**
67
+ * Applies a binary function to both values, collapsing the pair into a single value.
68
+ * Useful as the final step when consuming a pair in a pipeline.
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * pipe(Tuple.make("Alice", 100), Tuple.fold((name, score) => `${name}: ${score}`));
73
+ * // "Alice: 100"
74
+ * ```
75
+ */
76
+ Tuple.fold = (f) => (tuple) => f(tuple[0], tuple[1]);
77
+ /**
78
+ * Swaps the two values: `[A, B]` becomes `[B, A]`.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * Tuple.swap(Tuple.make("key", 1)); // [1, "key"]
83
+ * ```
84
+ */
85
+ Tuple.swap = (tuple) => [tuple[1], tuple[0]];
86
+ /**
87
+ * Converts the pair to a heterogeneous readonly array `readonly (A | B)[]`.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * Tuple.toArray(Tuple.make("hello", 42)); // ["hello", 42]
92
+ * ```
93
+ */
94
+ Tuple.toArray = (tuple) => [...tuple];
95
+ /**
96
+ * Runs a side effect with both values without changing the pair.
97
+ * Useful for logging or debugging in the middle of a pipeline.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * pipe(
102
+ * Tuple.make("Paris", 2_161_000),
103
+ * Tuple.tap((city, pop) => console.log(`${city}: ${pop}`)),
104
+ * Tuple.mapSecond((n) => n / 1_000_000),
105
+ * ); // logs "Paris: 2161000", returns ["Paris", 2.161]
106
+ * ```
107
+ */
108
+ Tuple.tap = (f) => (tuple) => {
109
+ f(tuple[0], tuple[1]);
110
+ return tuple;
111
+ };
112
+ })(Tuple || (Tuple = {}));
@@ -1,17 +1,18 @@
1
- export * from "./Logged.js";
2
1
  export * from "./Deferred.js";
3
2
  export * from "./Lens.js";
3
+ export * from "./Logged.js";
4
4
  export * from "./Option.js";
5
- export * from "./Reader.js";
6
5
  export * from "./Optional.js";
7
6
  export * from "./Predicate.js";
7
+ export * from "./Reader.js";
8
8
  export * from "./Refinement.js";
9
9
  export * from "./RemoteData.js";
10
- export * from "./State.js";
11
10
  export * from "./Result.js";
11
+ export * from "./State.js";
12
12
  export * from "./Task.js";
13
13
  export * from "./TaskOption.js";
14
14
  export * from "./TaskResult.js";
15
15
  export * from "./TaskValidation.js";
16
16
  export * from "./These.js";
17
+ export * from "./Tuple.js";
17
18
  export * from "./Validation.js";
@@ -0,0 +1,421 @@
1
+ import { Option } from "../Core/Option.js";
2
+ /**
3
+ * Functional utilities for key-value dictionaries (`ReadonlyMap<K, V>`). All functions are pure
4
+ * and data-last — they compose naturally with `pipe`.
5
+ *
6
+ * Unlike plain objects (`Rec`), dictionaries support any key type, preserve insertion order, and
7
+ * make membership checks explicit via `lookup` returning `Option`.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { Dict } from "@nlozgachev/pipelined/utils";
12
+ * import { pipe } from "@nlozgachev/pipelined/composition";
13
+ *
14
+ * const scores = pipe(
15
+ * Dict.fromEntries([["alice", 10], ["bob", 8], ["carol", 10]] as const),
16
+ * Dict.filter(n => n >= 10),
17
+ * Dict.map(n => `${n} points`),
18
+ * );
19
+ * // ReadonlyMap { "alice" => "10 points", "carol" => "10 points" }
20
+ * ```
21
+ */
22
+ export var Dict;
23
+ (function (Dict) {
24
+ // ---------------------------------------------------------------------------
25
+ // Constructors
26
+ // ---------------------------------------------------------------------------
27
+ /**
28
+ * Creates an empty dictionary.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * Dict.empty<string, number>(); // ReadonlyMap {}
33
+ * ```
34
+ */
35
+ Dict.empty = () => new globalThis.Map();
36
+ /**
37
+ * Creates a dictionary with a single entry.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * Dict.singleton("name", "Alice"); // ReadonlyMap { "name" => "Alice" }
42
+ * ```
43
+ */
44
+ Dict.singleton = (key, value) => new globalThis.Map([[key, value]]);
45
+ /**
46
+ * Creates a dictionary from an array of key-value pairs.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * Dict.fromEntries([["a", 1], ["b", 2]]); // ReadonlyMap { "a" => 1, "b" => 2 }
51
+ * ```
52
+ */
53
+ Dict.fromEntries = (entries) => new globalThis.Map(entries);
54
+ /**
55
+ * Creates a dictionary from a plain object. Keys are always strings.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * Dict.fromRecord({ a: 1, b: 2 }); // ReadonlyMap { "a" => 1, "b" => 2 }
60
+ * ```
61
+ */
62
+ Dict.fromRecord = (rec) => new globalThis.Map(Object.entries(rec));
63
+ /**
64
+ * Groups elements of an array into a dictionary keyed by the result of `keyFn`. Each key maps
65
+ * to the array of elements that produced it, in insertion order. Uses the native `Map.groupBy`
66
+ * when available, falling back to a manual loop in older environments.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * pipe(
71
+ * [{ name: "alice", role: "admin" }, { name: "bob", role: "viewer" }, { name: "carol", role: "admin" }],
72
+ * Dict.groupBy(user => user.role),
73
+ * );
74
+ * // ReadonlyMap { "admin" => [alice, carol], "viewer" => [bob] }
75
+ * ```
76
+ */
77
+ Dict.groupBy = (keyFn) => (items) => {
78
+ const result = new globalThis.Map();
79
+ for (const item of items) {
80
+ const key = keyFn(item);
81
+ const arr = result.get(key);
82
+ if (arr !== undefined)
83
+ arr.push(item);
84
+ else
85
+ result.set(key, [item]);
86
+ }
87
+ return result;
88
+ };
89
+ // ---------------------------------------------------------------------------
90
+ // Query
91
+ // ---------------------------------------------------------------------------
92
+ /**
93
+ * Returns `true` if the dictionary contains the given key.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * pipe(Dict.fromEntries([["a", 1]]), Dict.has("a")); // true
98
+ * pipe(Dict.fromEntries([["a", 1]]), Dict.has("b")); // false
99
+ * ```
100
+ */
101
+ Dict.has = (key) => (m) => m.has(key);
102
+ /**
103
+ * Looks up a value by key, returning `Some(value)` if found and `None` if not.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * pipe(Dict.fromEntries([["a", 1]]), Dict.lookup("a")); // Some(1)
108
+ * pipe(Dict.fromEntries([["a", 1]]), Dict.lookup("b")); // None
109
+ * ```
110
+ */
111
+ Dict.lookup = (key) => (m) => m.has(key) ? Option.some(m.get(key)) : Option.none();
112
+ /**
113
+ * Returns the number of entries in the dictionary.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * Dict.size(Dict.fromEntries([["a", 1], ["b", 2]])); // 2
118
+ * ```
119
+ */
120
+ Dict.size = (m) => m.size;
121
+ /**
122
+ * Returns `true` if the dictionary has no entries.
123
+ *
124
+ * @example
125
+ * ```ts
126
+ * Dict.isEmpty(Dict.empty()); // true
127
+ * ```
128
+ */
129
+ Dict.isEmpty = (m) => m.size === 0;
130
+ /**
131
+ * Returns all keys as a readonly array, in insertion order.
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * Dict.keys(Dict.fromEntries([["a", 1], ["b", 2]])); // ["a", "b"]
136
+ * ```
137
+ */
138
+ Dict.keys = (m) => [...m.keys()];
139
+ /**
140
+ * Returns all values as a readonly array, in insertion order.
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * Dict.values(Dict.fromEntries([["a", 1], ["b", 2]])); // [1, 2]
145
+ * ```
146
+ */
147
+ Dict.values = (m) => [...m.values()];
148
+ /**
149
+ * Returns all key-value pairs as a readonly array of tuples, in insertion order.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * Dict.entries(Dict.fromEntries([["a", 1], ["b", 2]])); // [["a", 1], ["b", 2]]
154
+ * ```
155
+ */
156
+ Dict.entries = (m) => [...m.entries()];
157
+ // ---------------------------------------------------------------------------
158
+ // Modification
159
+ // ---------------------------------------------------------------------------
160
+ /**
161
+ * Returns a new dictionary with the given key set to the given value.
162
+ * If the key already exists, its value is replaced.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * pipe(Dict.fromEntries([["a", 1]]), Dict.insert("b", 2));
167
+ * // ReadonlyMap { "a" => 1, "b" => 2 }
168
+ * ```
169
+ */
170
+ Dict.insert = (key, value) => (m) => {
171
+ const result = new globalThis.Map(m);
172
+ result.set(key, value);
173
+ return result;
174
+ };
175
+ /**
176
+ * Returns a new dictionary with the given key removed.
177
+ * If the key does not exist, the dictionary is returned unchanged.
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * pipe(Dict.fromEntries([["a", 1], ["b", 2]]), Dict.remove("a"));
182
+ * // ReadonlyMap { "b" => 2 }
183
+ * ```
184
+ */
185
+ Dict.remove = (key) => (m) => {
186
+ if (!m.has(key))
187
+ return m;
188
+ const result = new globalThis.Map(m);
189
+ result.delete(key);
190
+ return result;
191
+ };
192
+ /**
193
+ * Returns a new dictionary with the value at `key` set by `f`. If the key does not exist,
194
+ * `f` receives `None`. If the key exists, `f` receives `Some(currentValue)`.
195
+ *
196
+ * Useful for incrementing counters, initialising defaults, or conditional updates.
197
+ *
198
+ * @example
199
+ * ```ts
200
+ * import { Option } from "@nlozgachev/pipelined/core";
201
+ *
202
+ * const increment = (opt: Option<number>) => Option.getOrElse(() => 0)(opt) + 1;
203
+ * pipe(Dict.fromEntries([["views", 5]]), Dict.upsert("views", increment)); // { views: 6 }
204
+ * pipe(Dict.fromEntries([["views", 5]]), Dict.upsert("likes", increment)); // { views: 5, likes: 1 }
205
+ * ```
206
+ */
207
+ Dict.upsert = (key, f) => (m) => {
208
+ const result = new globalThis.Map(m);
209
+ result.set(key, f(Dict.lookup(key)(m)));
210
+ return result;
211
+ };
212
+ // ---------------------------------------------------------------------------
213
+ // Transform
214
+ // ---------------------------------------------------------------------------
215
+ /**
216
+ * Transforms each value in the dictionary.
217
+ *
218
+ * @example
219
+ * ```ts
220
+ * pipe(Dict.fromEntries([["a", 1], ["b", 2]]), Dict.map(n => n * 2));
221
+ * // ReadonlyMap { "a" => 2, "b" => 4 }
222
+ * ```
223
+ */
224
+ Dict.map = (f) => (m) => {
225
+ const result = new globalThis.Map();
226
+ for (const [k, v] of m) {
227
+ result.set(k, f(v));
228
+ }
229
+ return result;
230
+ };
231
+ /**
232
+ * Transforms each value in the dictionary, also receiving the key.
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * pipe(Dict.fromEntries([["a", 1], ["b", 2]]), Dict.mapWithKey((k, v) => `${k}:${v}`));
237
+ * // ReadonlyMap { "a" => "a:1", "b" => "b:2" }
238
+ * ```
239
+ */
240
+ Dict.mapWithKey = (f) => (m) => {
241
+ const result = new globalThis.Map();
242
+ for (const [k, v] of m) {
243
+ result.set(k, f(k, v));
244
+ }
245
+ return result;
246
+ };
247
+ /**
248
+ * Returns a new dictionary containing only the entries for which the predicate returns `true`.
249
+ *
250
+ * @example
251
+ * ```ts
252
+ * pipe(Dict.fromEntries([["a", 1], ["b", 3], ["c", 0]]), Dict.filter(n => n > 0));
253
+ * // ReadonlyMap { "a" => 1, "b" => 3 }
254
+ * ```
255
+ */
256
+ Dict.filter = (predicate) => (m) => {
257
+ const result = new globalThis.Map();
258
+ for (const [k, v] of m) {
259
+ if (predicate(v))
260
+ result.set(k, v);
261
+ }
262
+ return result;
263
+ };
264
+ /**
265
+ * Returns a new dictionary containing only the entries for which the predicate returns `true`.
266
+ * The predicate also receives the key.
267
+ *
268
+ * @example
269
+ * ```ts
270
+ * pipe(Dict.fromEntries([["a", 1], ["b", 2]]), Dict.filterWithKey((k, v) => k !== "a" && v > 0));
271
+ * // ReadonlyMap { "b" => 2 }
272
+ * ```
273
+ */
274
+ Dict.filterWithKey = (predicate) => (m) => {
275
+ const result = new globalThis.Map();
276
+ for (const [k, v] of m) {
277
+ if (predicate(k, v))
278
+ result.set(k, v);
279
+ }
280
+ return result;
281
+ };
282
+ /**
283
+ * Removes all `None` values from a `ReadonlyMap<K, Option<A>>`, returning a plain
284
+ * `ReadonlyMap<K, A>`. Useful when building dictionaries from fallible lookups.
285
+ *
286
+ * @example
287
+ * ```ts
288
+ * import { Option } from "@nlozgachev/pipelined/core";
289
+ *
290
+ * Dict.compact(Dict.fromEntries([
291
+ * ["a", Option.some(1)],
292
+ * ["b", Option.none()],
293
+ * ["c", Option.some(3)],
294
+ * ]));
295
+ * // ReadonlyMap { "a" => 1, "c" => 3 }
296
+ * ```
297
+ */
298
+ Dict.compact = (m) => {
299
+ const result = new globalThis.Map();
300
+ for (const [k, v] of m) {
301
+ if (v.kind === "Some")
302
+ result.set(k, v.value);
303
+ }
304
+ return result;
305
+ };
306
+ // ---------------------------------------------------------------------------
307
+ // Combine
308
+ // ---------------------------------------------------------------------------
309
+ /**
310
+ * Merges two dictionaries. When both contain the same key, the value from `other` takes
311
+ * precedence.
312
+ *
313
+ * @example
314
+ * ```ts
315
+ * pipe(
316
+ * Dict.fromEntries([["a", 1], ["b", 2]]),
317
+ * Dict.union(Dict.fromEntries([["b", 3], ["c", 4]])),
318
+ * );
319
+ * // ReadonlyMap { "a" => 1, "b" => 3, "c" => 4 }
320
+ * ```
321
+ */
322
+ Dict.union = (other) => (m) => {
323
+ const result = new globalThis.Map(m);
324
+ for (const [k, v] of other) {
325
+ result.set(k, v);
326
+ }
327
+ return result;
328
+ };
329
+ /**
330
+ * Returns a new dictionary containing only the entries whose keys appear in both dictionaries.
331
+ * Values are taken from the left (base) dictionary.
332
+ *
333
+ * @example
334
+ * ```ts
335
+ * pipe(
336
+ * Dict.fromEntries([["a", 1], ["b", 2], ["c", 3]]),
337
+ * Dict.intersection(Dict.fromEntries([["b", 99], ["c", 0]])),
338
+ * );
339
+ * // ReadonlyMap { "b" => 2, "c" => 3 }
340
+ * ```
341
+ */
342
+ Dict.intersection = (other) => (m) => {
343
+ const result = new globalThis.Map();
344
+ for (const [k, v] of m) {
345
+ if (other.has(k))
346
+ result.set(k, v);
347
+ }
348
+ return result;
349
+ };
350
+ /**
351
+ * Returns a new dictionary containing only the entries whose keys do not appear in `other`.
352
+ *
353
+ * @example
354
+ * ```ts
355
+ * pipe(
356
+ * Dict.fromEntries([["a", 1], ["b", 2], ["c", 3]]),
357
+ * Dict.difference(Dict.fromEntries([["b", 0]])),
358
+ * );
359
+ * // ReadonlyMap { "a" => 1, "c" => 3 }
360
+ * ```
361
+ */
362
+ Dict.difference = (other) => (m) => {
363
+ const result = new globalThis.Map();
364
+ for (const [k, v] of m) {
365
+ if (!other.has(k))
366
+ result.set(k, v);
367
+ }
368
+ return result;
369
+ };
370
+ // ---------------------------------------------------------------------------
371
+ // Fold
372
+ // ---------------------------------------------------------------------------
373
+ /**
374
+ * Folds the dictionary into a single value by applying `f` to each value in insertion order.
375
+ * When you also need the key, use `reduceWithKey`.
376
+ *
377
+ * @example
378
+ * ```ts
379
+ * Dict.reduce(0, (acc, value) => acc + value)(
380
+ * Dict.fromEntries([["a", 1], ["b", 2], ["c", 3]])
381
+ * ); // 6
382
+ * ```
383
+ */
384
+ Dict.reduce = (init, f) => (m) => {
385
+ let acc = init;
386
+ for (const v of m.values()) {
387
+ acc = f(acc, v);
388
+ }
389
+ return acc;
390
+ };
391
+ /**
392
+ * Folds the dictionary into a single value by applying `f` to each key-value pair in insertion
393
+ * order.
394
+ *
395
+ * @example
396
+ * ```ts
397
+ * Dict.reduceWithKey("", (acc, value, key) => acc + key + ":" + value + " ")(
398
+ * Dict.fromEntries([["a", 1], ["b", 2]])
399
+ * ); // "a:1 b:2 "
400
+ * ```
401
+ */
402
+ Dict.reduceWithKey = (init, f) => (m) => {
403
+ let acc = init;
404
+ for (const [k, v] of m) {
405
+ acc = f(acc, v, k);
406
+ }
407
+ return acc;
408
+ };
409
+ // ---------------------------------------------------------------------------
410
+ // Convert
411
+ // ---------------------------------------------------------------------------
412
+ /**
413
+ * Converts a `ReadonlyMap<string, V>` to a plain object. Only meaningful when keys are strings.
414
+ *
415
+ * @example
416
+ * ```ts
417
+ * Dict.toRecord(Dict.fromEntries([["a", 1], ["b", 2]])); // { a: 1, b: 2 }
418
+ * ```
419
+ */
420
+ Dict.toRecord = (m) => Object.fromEntries(m);
421
+ })(Dict || (Dict = {}));
@@ -117,6 +117,32 @@ export var Rec;
117
117
  * ```
118
118
  */
119
119
  Rec.fromEntries = (data) => Object.fromEntries(data);
120
+ /**
121
+ * Groups elements of an array into a record keyed by the result of `keyFn`. Each key maps to
122
+ * the array of elements that produced it, in insertion order.
123
+ *
124
+ * Unlike `Dict.groupBy`, keys are always strings. Use `Dict.groupBy` when you need non-string
125
+ * keys or want to avoid the plain-object prototype chain.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * pipe(
130
+ * ["apple", "avocado", "banana", "blueberry"],
131
+ * Rec.groupBy(s => s[0]),
132
+ * ); // { a: ["apple", "avocado"], b: ["banana", "blueberry"] }
133
+ * ```
134
+ */
135
+ Rec.groupBy = (keyFn) => (items) => {
136
+ const result = {};
137
+ for (const item of items) {
138
+ const key = keyFn(item);
139
+ if (key in result)
140
+ result[key].push(item);
141
+ else
142
+ result[key] = [item];
143
+ }
144
+ return result;
145
+ };
120
146
  /**
121
147
  * Picks specific keys from a record.
122
148
  *