@mark1russell7/vex 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/build/index.d.ts +884 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +1839 -0
- package/build/index.js.map +1 -0
- package/package.json +44 -3
- package/src/builder.ts +649 -0
- package/src/deps.ts +33 -0
- package/src/domain.ts +135 -0
- package/src/errors.ts +102 -0
- package/src/evaluate.ts +628 -0
- package/src/index.ts +16 -0
- package/src/ir.ts +212 -0
- package/src/json.ts +76 -0
- package/src/list.ts +35 -0
- package/src/result.ts +44 -0
- package/src/sheet.ts +141 -0
- package/src/space.ts +322 -0
- package/src/trace.ts +37 -0
- package/src/traversal.ts +126 -0
- package/README.md +0 -3
package/src/space.ts
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { vexError } from "./errors.ts";
|
|
2
|
+
import type { Addr, Axis, Move } from "./ir.ts";
|
|
3
|
+
import { fail, ok, type Result } from "./result.ts";
|
|
4
|
+
|
|
5
|
+
/** The kind of a space. The kind sets which moves and axes are valid. */
|
|
6
|
+
export type SpaceKind = "record" | "array" | "grid" | "tree";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A space: an immutable collection of records with keys. A Vex program evaluates at one key of a space.
|
|
10
|
+
* Nothing changes a space after it is made.
|
|
11
|
+
*/
|
|
12
|
+
export interface Space<K extends string = string, O = unknown> {
|
|
13
|
+
readonly kind: SpaceKind;
|
|
14
|
+
/** The keys, in their order. */
|
|
15
|
+
readonly keys: readonly K[];
|
|
16
|
+
/** This function tells if the space has the key `k`. */
|
|
17
|
+
has(k: string): k is K;
|
|
18
|
+
/** This function gives the record at the key `k`, or `undefined`. */
|
|
19
|
+
get(k: string): O | undefined;
|
|
20
|
+
/** The position of each key, for array and grid spaces. An array key has one number, a grid key has two. */
|
|
21
|
+
coords(k: string): readonly number[] | undefined;
|
|
22
|
+
/** The key at a position, or `undefined`. */
|
|
23
|
+
keyAt(coords: readonly number[]): K | undefined;
|
|
24
|
+
/** The parent of the key `k` in a tree space, or `undefined` for a root. Other spaces do not have it. */
|
|
25
|
+
parentOf?(k: string): K | undefined;
|
|
26
|
+
/** The children of the key `k` in a tree space, in key order. Other spaces do not have it. */
|
|
27
|
+
childrenOf?(k: string): readonly K[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The key type of a grid space. */
|
|
31
|
+
export type GridKey = `${number},${number}`;
|
|
32
|
+
|
|
33
|
+
/** The key type of an array space. */
|
|
34
|
+
export type ArrayKey = `${number}`;
|
|
35
|
+
|
|
36
|
+
class RecordSpace<K extends string, O> implements Space<K, O> {
|
|
37
|
+
readonly kind: SpaceKind = "record";
|
|
38
|
+
readonly keys: readonly K[];
|
|
39
|
+
readonly #records: ReadonlyMap<string, O>;
|
|
40
|
+
|
|
41
|
+
constructor(records: Readonly<Record<K, O>>) {
|
|
42
|
+
const entries = Object.entries(records) as [K, O][];
|
|
43
|
+
this.keys = Object.freeze(entries.map(([k]) => k));
|
|
44
|
+
this.#records = new Map(entries);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
has(k: string): k is K {
|
|
48
|
+
return this.#records.has(k);
|
|
49
|
+
}
|
|
50
|
+
get(k: string): O | undefined {
|
|
51
|
+
return this.#records.get(k);
|
|
52
|
+
}
|
|
53
|
+
coords(): readonly number[] | undefined {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
keyAt(): K | undefined {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
class ArraySpace<O> implements Space<ArrayKey, O> {
|
|
62
|
+
readonly kind: SpaceKind = "array";
|
|
63
|
+
readonly keys: readonly ArrayKey[];
|
|
64
|
+
readonly #items: ReadonlyMap<string, O>;
|
|
65
|
+
|
|
66
|
+
constructor(items: readonly O[]) {
|
|
67
|
+
const entries = items.map((item, i): [ArrayKey, O] => [`${i}`, item]);
|
|
68
|
+
this.keys = Object.freeze(entries.map(([k]) => k));
|
|
69
|
+
this.#items = new Map(entries);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
has(k: string): k is ArrayKey {
|
|
73
|
+
return this.#items.has(k);
|
|
74
|
+
}
|
|
75
|
+
get(k: string): O | undefined {
|
|
76
|
+
return this.#items.get(k);
|
|
77
|
+
}
|
|
78
|
+
coords(k: string): readonly number[] | undefined {
|
|
79
|
+
return this.has(k) ? [Number(k)] : undefined;
|
|
80
|
+
}
|
|
81
|
+
keyAt(coords: readonly number[]): ArrayKey | undefined {
|
|
82
|
+
const k = coords.join(",");
|
|
83
|
+
return coords.length === 1 && this.has(k) ? k : undefined;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
class GridSpace<O> implements Space<GridKey, O> {
|
|
88
|
+
readonly kind: SpaceKind = "grid";
|
|
89
|
+
readonly keys: readonly GridKey[];
|
|
90
|
+
readonly #cells: ReadonlyMap<string, O>;
|
|
91
|
+
readonly #coords: ReadonlyMap<string, readonly number[]>;
|
|
92
|
+
|
|
93
|
+
constructor(rows: readonly (readonly O[])[]) {
|
|
94
|
+
const entries = rows.flatMap((row, i) => row.map((cell, j): [GridKey, O, readonly number[]] => [`${i},${j}`, cell, Object.freeze([i, j])]));
|
|
95
|
+
this.keys = Object.freeze(entries.map(([k]) => k));
|
|
96
|
+
this.#cells = new Map(entries.map(([k, cell]) => [k, cell]));
|
|
97
|
+
this.#coords = new Map(entries.map(([k, , c]) => [k, c]));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
has(k: string): k is GridKey {
|
|
101
|
+
return this.#cells.has(k);
|
|
102
|
+
}
|
|
103
|
+
get(k: string): O | undefined {
|
|
104
|
+
return this.#cells.get(k);
|
|
105
|
+
}
|
|
106
|
+
coords(k: string): readonly number[] | undefined {
|
|
107
|
+
return this.#coords.get(k);
|
|
108
|
+
}
|
|
109
|
+
keyAt(coords: readonly number[]): GridKey | undefined {
|
|
110
|
+
const k = coords.join(",");
|
|
111
|
+
return coords.length === 2 && this.has(k) ? k : undefined;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
class TreeSpace<K extends string, O> implements Space<K, O> {
|
|
116
|
+
readonly kind: SpaceKind = "tree";
|
|
117
|
+
readonly keys: readonly K[];
|
|
118
|
+
readonly #records: ReadonlyMap<string, O>;
|
|
119
|
+
readonly #parents: ReadonlyMap<string, K>;
|
|
120
|
+
readonly #children: ReadonlyMap<string, readonly K[]>;
|
|
121
|
+
|
|
122
|
+
constructor(records: Readonly<Record<K, O>>, parents: Readonly<Partial<Record<K, K | null>>>) {
|
|
123
|
+
const entries = Object.entries(records) as [K, O][];
|
|
124
|
+
this.keys = Object.freeze(entries.map(([k]) => k));
|
|
125
|
+
this.#records = new Map(entries);
|
|
126
|
+
const parentOf = new Map<string, K>();
|
|
127
|
+
for (const [k, p] of Object.entries(parents) as [K, K | null | undefined][]) {
|
|
128
|
+
if (!this.#records.has(k)) throw new TypeError(`the tree has no key "${k}", but the parents name it`);
|
|
129
|
+
if (p === null || p === undefined) continue;
|
|
130
|
+
if (!this.#records.has(p)) throw new TypeError(`the parent "${p}" of "${k}" is not a key of the tree`);
|
|
131
|
+
parentOf.set(k, p);
|
|
132
|
+
}
|
|
133
|
+
// A parent chain that comes back to a key of the same walk is a cycle, not a tree. Each key is in one walk
|
|
134
|
+
// only: a walk stops at a key that an earlier walk proved to reach a root. Thus the check is linear.
|
|
135
|
+
const reachesRoot = new Set<string>();
|
|
136
|
+
for (const k of this.keys) {
|
|
137
|
+
const walk = new Set<string>();
|
|
138
|
+
for (let p: string | undefined = k; p !== undefined && !reachesRoot.has(p); p = parentOf.get(p)) {
|
|
139
|
+
if (walk.has(p)) throw new TypeError(`the parents of "${k}" make a cycle, so the space is not a tree`);
|
|
140
|
+
walk.add(p);
|
|
141
|
+
}
|
|
142
|
+
for (const w of walk) reachesRoot.add(w);
|
|
143
|
+
}
|
|
144
|
+
this.#parents = parentOf;
|
|
145
|
+
const children = new Map<string, K[]>(this.keys.map((k) => [k, []]));
|
|
146
|
+
for (const k of this.keys) {
|
|
147
|
+
const p = parentOf.get(k);
|
|
148
|
+
if (p !== undefined) children.get(p)?.push(k);
|
|
149
|
+
}
|
|
150
|
+
this.#children = new Map([...children].map(([k, c]) => [k, Object.freeze(c)]));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
has(k: string): k is K {
|
|
154
|
+
return this.#records.has(k);
|
|
155
|
+
}
|
|
156
|
+
get(k: string): O | undefined {
|
|
157
|
+
return this.#records.get(k);
|
|
158
|
+
}
|
|
159
|
+
coords(): readonly number[] | undefined {
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
keyAt(): K | undefined {
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
parentOf(k: string): K | undefined {
|
|
166
|
+
return this.#parents.get(k);
|
|
167
|
+
}
|
|
168
|
+
childrenOf(k: string): readonly K[] {
|
|
169
|
+
return this.#children.get(k) ?? [];
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The constructors of spaces. */
|
|
174
|
+
export const space = {
|
|
175
|
+
/** This function makes a space from the entries of an object. The keys are the property names. */
|
|
176
|
+
record<const R extends Readonly<Record<string, unknown>>>(records: R): Space<keyof R & string, R[keyof R]> {
|
|
177
|
+
return new RecordSpace<keyof R & string, R[keyof R]>(records);
|
|
178
|
+
},
|
|
179
|
+
/** This function makes a space from an array. The keys are `"0"`, `"1"` and so on. */
|
|
180
|
+
array<O>(items: readonly O[]): Space<ArrayKey, O> {
|
|
181
|
+
return new ArraySpace(items);
|
|
182
|
+
},
|
|
183
|
+
/** This function makes a space from rows of cells. The key of a cell is `"row,column"`. */
|
|
184
|
+
grid<O>(rows: readonly (readonly O[])[]): Space<GridKey, O> {
|
|
185
|
+
return new GridSpace(rows);
|
|
186
|
+
},
|
|
187
|
+
/**
|
|
188
|
+
* This function makes a tree space: the records by key, and the parent of each key. A key without a parent, or
|
|
189
|
+
* with the parent `null`, is a root. A parent that is not a key, or a cycle of parents, throws a `TypeError`.
|
|
190
|
+
*/
|
|
191
|
+
tree<const R extends Readonly<Record<string, unknown>>>(records: R, parents: Readonly<Partial<Record<keyof R & string, (keyof R & string) | null>>>): Space<keyof R & string, R[keyof R]> {
|
|
192
|
+
return new TreeSpace<keyof R & string, R[keyof R]>(records, parents);
|
|
193
|
+
},
|
|
194
|
+
} as const;
|
|
195
|
+
|
|
196
|
+
/** The position of an evaluation: the key where it started, and the key where relative references read. */
|
|
197
|
+
export interface Position {
|
|
198
|
+
readonly origin: string;
|
|
199
|
+
readonly focus: string;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** This function applies one move to the focus. It gives the new focus, or a `#REF!` error. */
|
|
203
|
+
export function applyMove(s: Space, at: Position, m: Move): Result<string> {
|
|
204
|
+
const refError = (kind: "unknown-key" | "not-a-pair" | "out-of-bounds" | "no-offset" | "no-tree", message: string): Result<string> =>
|
|
205
|
+
fail(vexError(kind, message, { origin: at.origin, focus: at.focus }));
|
|
206
|
+
switch (m.t) {
|
|
207
|
+
case "key":
|
|
208
|
+
return s.has(m.key) ? ok(m.key) : refError("unknown-key", `the space has no key "${m.key}"`);
|
|
209
|
+
case "index": {
|
|
210
|
+
const k = s.keys[m.i];
|
|
211
|
+
return m.i >= 0 && k !== undefined ? ok(k) : refError("out-of-bounds", `the space has no key at index ${m.i}`);
|
|
212
|
+
}
|
|
213
|
+
case "other": {
|
|
214
|
+
if (s.keys.length !== 2) return refError("not-a-pair", `"other" needs a space with 2 keys, but this space has ${s.keys.length}`);
|
|
215
|
+
const [a, b] = s.keys;
|
|
216
|
+
// A pair has two keys, so `a` and `b` are defined.
|
|
217
|
+
/* v8 ignore next -- @preserve */
|
|
218
|
+
return ok(at.focus === a ? (b ?? at.focus) : (a ?? at.focus));
|
|
219
|
+
}
|
|
220
|
+
case "offset": {
|
|
221
|
+
const c = s.coords(at.focus);
|
|
222
|
+
if (c === undefined || c.length !== m.d.length) {
|
|
223
|
+
return refError("no-offset", `an offset of length ${m.d.length} is not valid in a ${s.kind} space`);
|
|
224
|
+
}
|
|
225
|
+
// The lengths are equal, so each index of `c` is also an index of `m.d`.
|
|
226
|
+
/* v8 ignore next -- @preserve */
|
|
227
|
+
const target = c.map((x, i) => x + (m.d[i] ?? 0));
|
|
228
|
+
const k = s.keyAt(target);
|
|
229
|
+
return k === undefined ? refError("out-of-bounds", `the offset [${m.d.join(",")}] from "${at.focus}" is outside the space`) : ok(k);
|
|
230
|
+
}
|
|
231
|
+
case "origin":
|
|
232
|
+
return ok(at.origin);
|
|
233
|
+
case "parent": {
|
|
234
|
+
if (s.parentOf === undefined) return refError("no-tree", `"parent" needs a tree space, but this space is a ${s.kind}`);
|
|
235
|
+
const p = s.parentOf(at.focus);
|
|
236
|
+
return p === undefined ? refError("out-of-bounds", `the key "${at.focus}" is a root, so it has no parent`) : ok(p);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** This function applies the moves of an address in order. It gives the key where the address points. */
|
|
242
|
+
export function resolveAddr(s: Space, at: Position, addr: Addr | undefined): Result<string> {
|
|
243
|
+
let focus = at.focus;
|
|
244
|
+
for (const m of addr ?? []) {
|
|
245
|
+
const r = applyMove(s, { origin: at.origin, focus }, m);
|
|
246
|
+
if (!r.ok) return r;
|
|
247
|
+
focus = r.value;
|
|
248
|
+
}
|
|
249
|
+
return ok(focus);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const NEIGHBORS_4: readonly (readonly [number, number])[] = [[-1, 0], [0, -1], [0, 1], [1, 0]];
|
|
253
|
+
const NEIGHBORS_8: readonly (readonly [number, number])[] = [
|
|
254
|
+
[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1],
|
|
255
|
+
];
|
|
256
|
+
|
|
257
|
+
/** The axes of a tree space. */
|
|
258
|
+
type TreeAxis = "children" | "ancestors" | "descendants" | "siblings";
|
|
259
|
+
|
|
260
|
+
function treeTargets(s: Space, at: Position, t: TreeAxis): Result<readonly string[]> {
|
|
261
|
+
const parentOf = s.parentOf?.bind(s);
|
|
262
|
+
const childrenOf = s.childrenOf?.bind(s);
|
|
263
|
+
if (parentOf === undefined || childrenOf === undefined) {
|
|
264
|
+
return fail(vexError("no-tree", `"${t}" needs a tree space, but this space is a ${s.kind}`, at));
|
|
265
|
+
}
|
|
266
|
+
switch (t) {
|
|
267
|
+
case "children":
|
|
268
|
+
return ok(childrenOf(at.focus));
|
|
269
|
+
case "ancestors": {
|
|
270
|
+
const out: string[] = [];
|
|
271
|
+
for (let p = parentOf(at.focus); p !== undefined; p = parentOf(p)) out.push(p);
|
|
272
|
+
return ok(out);
|
|
273
|
+
}
|
|
274
|
+
case "descendants": {
|
|
275
|
+
// A depth-first walk with a stack, so a deep tree does not need a deep call stack.
|
|
276
|
+
const out: string[] = [];
|
|
277
|
+
const stack = childrenOf(at.focus).toReversed();
|
|
278
|
+
for (let k = stack.pop(); k !== undefined; k = stack.pop()) {
|
|
279
|
+
out.push(k);
|
|
280
|
+
stack.push(...childrenOf(k).toReversed());
|
|
281
|
+
}
|
|
282
|
+
return ok(out);
|
|
283
|
+
}
|
|
284
|
+
case "siblings": {
|
|
285
|
+
const p = parentOf(at.focus);
|
|
286
|
+
const group = p === undefined ? s.keys.filter((k) => parentOf(k) === undefined) : childrenOf(p);
|
|
287
|
+
return ok(group.filter((k) => k !== at.focus));
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* This function gives the targets of a base axis at a focus. It does not handle `where`, because the
|
|
294
|
+
* interpreter must evaluate the test.
|
|
295
|
+
*/
|
|
296
|
+
export function axisTargets(s: Space, at: Position, a: Exclude<Axis, { readonly t: "where" }>): Result<readonly string[]> {
|
|
297
|
+
switch (a.t) {
|
|
298
|
+
case "all":
|
|
299
|
+
return ok(s.keys);
|
|
300
|
+
case "others":
|
|
301
|
+
return ok(s.keys.filter((k) => k !== at.focus));
|
|
302
|
+
case "other": {
|
|
303
|
+
const r = applyMove(s, at, { t: "other" });
|
|
304
|
+
return r.ok ? ok([r.value]) : r;
|
|
305
|
+
}
|
|
306
|
+
case "neighbors": {
|
|
307
|
+
if (s.kind !== "grid") return fail(vexError("no-grid", `"neighbors" needs a grid space, but this space is a ${s.kind}`, at));
|
|
308
|
+
const deltas = a.n === 4 ? NEIGHBORS_4 : NEIGHBORS_8;
|
|
309
|
+
return ok(
|
|
310
|
+
deltas.flatMap((d) => {
|
|
311
|
+
const r = applyMove(s, at, { t: "offset", d });
|
|
312
|
+
return r.ok ? [r.value] : [];
|
|
313
|
+
}),
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
case "children":
|
|
317
|
+
case "ancestors":
|
|
318
|
+
case "descendants":
|
|
319
|
+
case "siblings":
|
|
320
|
+
return treeTargets(s, at, a.t);
|
|
321
|
+
}
|
|
322
|
+
}
|
package/src/trace.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { ExprTag } from "./ir.ts";
|
|
2
|
+
import type { Result } from "./result.ts";
|
|
3
|
+
|
|
4
|
+
/** One field read of a reference: the key and the path that it read, and if the read found a value. */
|
|
5
|
+
export interface Read {
|
|
6
|
+
readonly key: string;
|
|
7
|
+
readonly path: readonly string[];
|
|
8
|
+
readonly ok: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** The record of one node evaluation. The interpreter makes one event each time it evaluates a node. */
|
|
12
|
+
export interface TraceEvent {
|
|
13
|
+
/** The position of the node in the expression tree. */
|
|
14
|
+
readonly path: readonly number[];
|
|
15
|
+
readonly tag: ExprTag;
|
|
16
|
+
/** A short text for the node: the op name, the variable name or the field path. */
|
|
17
|
+
readonly label: string;
|
|
18
|
+
/** The key where the evaluation started. */
|
|
19
|
+
readonly origin: string;
|
|
20
|
+
/** The key where relative references read. Inside an axis, this is the target. */
|
|
21
|
+
readonly focus: string;
|
|
22
|
+
/** The field reads of a reference node. */
|
|
23
|
+
readonly reads?: readonly Read[];
|
|
24
|
+
/** The result of the node. */
|
|
25
|
+
readonly result: Result<unknown>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A trace: the events of one evaluation, in the order that the nodes finished. */
|
|
29
|
+
export interface Trace {
|
|
30
|
+
readonly events: readonly TraceEvent[];
|
|
31
|
+
readonly result: Result<unknown>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A receiver of trace events. */
|
|
35
|
+
export interface TraceSink {
|
|
36
|
+
readonly events: TraceEvent[];
|
|
37
|
+
}
|
package/src/traversal.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { AnyDomain } from "./domain.ts";
|
|
2
|
+
import { vexError, type VexError } from "./errors.ts";
|
|
3
|
+
import { evaluate, type FreeFn } from "./evaluate.ts";
|
|
4
|
+
import { app, lit, v } from "./ir.ts";
|
|
5
|
+
import { vexList, type ListItem } from "./list.ts";
|
|
6
|
+
import { fail, ok, toOptional, type Optional, type Result } from "./result.ts";
|
|
7
|
+
import { space as spaces, type Space } from "./space.ts";
|
|
8
|
+
|
|
9
|
+
/** A monoid: an associative `concat` with an identity element `empty`. */
|
|
10
|
+
export interface Monoid<M> {
|
|
11
|
+
readonly empty: M;
|
|
12
|
+
readonly concat: (a: M, b: M) => M;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Standard monoids. */
|
|
16
|
+
export const monoids: {
|
|
17
|
+
readonly sum: Monoid<number>;
|
|
18
|
+
readonly product: Monoid<number>;
|
|
19
|
+
readonly all: Monoid<boolean>;
|
|
20
|
+
readonly any: Monoid<boolean>;
|
|
21
|
+
} = {
|
|
22
|
+
sum: { empty: 0, concat: (a, b) => a + b },
|
|
23
|
+
product: { empty: 1, concat: (a, b) => a * b },
|
|
24
|
+
all: { empty: true, concat: (a, b) => a && b },
|
|
25
|
+
any: { empty: false, concat: (a, b) => a || b },
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** One item of a traversal: the start key and the result there. */
|
|
29
|
+
export interface TraversalItem<K extends string, T> {
|
|
30
|
+
readonly key: K;
|
|
31
|
+
readonly result: Result<T>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A traversal: the results of one program at each start key. The reductions skip error items by default.
|
|
36
|
+
* After `strict()`, an error item makes the reduction that error.
|
|
37
|
+
*/
|
|
38
|
+
export interface Traversal<K extends string, T> {
|
|
39
|
+
readonly items: readonly TraversalItem<K, T>[];
|
|
40
|
+
/** This method gives a traversal whose reductions fail on the first error item. */
|
|
41
|
+
strict(): Traversal<K, T>;
|
|
42
|
+
/** This method gives the result at one key. */
|
|
43
|
+
get(k: K): Optional<T>;
|
|
44
|
+
/** The values of the items without errors. */
|
|
45
|
+
values(): readonly T[];
|
|
46
|
+
/** The keys of the items without errors. */
|
|
47
|
+
keys(): readonly K[];
|
|
48
|
+
/** The errors of the items with errors. */
|
|
49
|
+
errors(): readonly VexError[];
|
|
50
|
+
count(): Optional<number>;
|
|
51
|
+
sum(this: Traversal<K, number>): Optional<number>;
|
|
52
|
+
mean(this: Traversal<K, number>): Optional<number>;
|
|
53
|
+
min(this: Traversal<K, number>): Optional<number>;
|
|
54
|
+
max(this: Traversal<K, number>): Optional<number>;
|
|
55
|
+
any(this: Traversal<K, boolean>): Optional<boolean>;
|
|
56
|
+
all(this: Traversal<K, boolean>): Optional<boolean>;
|
|
57
|
+
none(this: Traversal<K, boolean>): Optional<boolean>;
|
|
58
|
+
/** This method folds the values with a domain op, from the left. */
|
|
59
|
+
reduce(op: string): Optional<T>;
|
|
60
|
+
/** This method gives the result of a reduction, with its error. */
|
|
61
|
+
reduceResult(op: "count" | "sum" | "mean" | "min" | "max" | "any" | "all" | "none" | "reduce", reduceOp?: string): Result<unknown>;
|
|
62
|
+
/** This method maps each value with `f`. If `f` throws, the item has the error `#CALC!`. */
|
|
63
|
+
map<U>(f: (value: T, key: K) => U): Traversal<K, U>;
|
|
64
|
+
/** This method folds the values with a monoid. */
|
|
65
|
+
fold<M>(monoid: Monoid<M>, f: (value: T) => M): M;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface TraversalEnv {
|
|
69
|
+
readonly domains: readonly AnyDomain[];
|
|
70
|
+
readonly options?: { readonly fns?: Readonly<Record<string, FreeFn>> };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const EMPTY_SPACE: Space = spaces.record({ $: {} });
|
|
74
|
+
|
|
75
|
+
const opt = <U>(r: Result<unknown>): Optional<U> => toOptional(r as Result<U>);
|
|
76
|
+
|
|
77
|
+
/** This function makes a traversal from items. */
|
|
78
|
+
export function traversal<K extends string, T>(items: readonly TraversalItem<K, T>[], env: TraversalEnv, isStrict = false): Traversal<K, T> {
|
|
79
|
+
const reduce = (op: string, reduceOp?: string): Result<unknown> => {
|
|
80
|
+
const list = vexList(items as readonly ListItem[]);
|
|
81
|
+
const args = [v("$list"), ...(reduceOp === undefined ? [] : [lit(reduceOp)]), ...(isStrict ? [lit({ strict: true })] : [])];
|
|
82
|
+
return evaluate(app(op, ...args), {
|
|
83
|
+
space: EMPTY_SPACE,
|
|
84
|
+
origin: "$",
|
|
85
|
+
domains: env.domains,
|
|
86
|
+
vars: { $list: list },
|
|
87
|
+
...(env.options?.fns === undefined ? {} : { fns: env.options.fns }),
|
|
88
|
+
});
|
|
89
|
+
};
|
|
90
|
+
const t: Traversal<K, T> = {
|
|
91
|
+
items,
|
|
92
|
+
strict: () => traversal(items, env, true),
|
|
93
|
+
get: (k) => {
|
|
94
|
+
const item = items.find((it) => it.key === k);
|
|
95
|
+
return item === undefined ? toOptional(fail(vexError("unknown-key", `no item has the key "${k}"`))) : toOptional(item.result);
|
|
96
|
+
},
|
|
97
|
+
values: () => items.flatMap((it) => (it.result.ok ? [it.result.value] : [])),
|
|
98
|
+
keys: () => items.flatMap((it) => (it.result.ok ? [it.key] : [])),
|
|
99
|
+
errors: () => items.flatMap((it) => (it.result.ok ? [] : [it.result.error])),
|
|
100
|
+
count: () => opt(reduce("count")),
|
|
101
|
+
sum: () => opt(reduce("sum")),
|
|
102
|
+
mean: () => opt(reduce("mean")),
|
|
103
|
+
min: () => opt(reduce("min")),
|
|
104
|
+
max: () => opt(reduce("max")),
|
|
105
|
+
any: () => opt(reduce("any")),
|
|
106
|
+
all: () => opt(reduce("all")),
|
|
107
|
+
none: () => opt(reduce("none")),
|
|
108
|
+
reduce: (op) => opt(reduce("reduce", op)),
|
|
109
|
+
reduceResult: (op, reduceOp) => reduce(op, reduceOp),
|
|
110
|
+
map: <U>(f: (value: T, key: K) => U): Traversal<K, U> =>
|
|
111
|
+
traversal(
|
|
112
|
+
items.map((it): TraversalItem<K, U> => {
|
|
113
|
+
if (!it.result.ok) return { key: it.key, result: it.result };
|
|
114
|
+
try {
|
|
115
|
+
return { key: it.key, result: ok(f(it.result.value, it.key)) };
|
|
116
|
+
} catch (thrown) {
|
|
117
|
+
return { key: it.key, result: fail(vexError("threw", "the map function threw an exception", { thrown, focus: it.key })) };
|
|
118
|
+
}
|
|
119
|
+
}),
|
|
120
|
+
env,
|
|
121
|
+
isStrict,
|
|
122
|
+
),
|
|
123
|
+
fold: <M>(monoid: Monoid<M>, f: (value: T) => M): M => t.values().reduce((acc, x) => monoid.concat(acc, f(x)), monoid.empty),
|
|
124
|
+
};
|
|
125
|
+
return t;
|
|
126
|
+
}
|
package/README.md
DELETED