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