trilean 1.1.0 → 1.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 +130 -19
- package/dist/complex.cjs +34 -0
- package/dist/complex.d.cts +23 -0
- package/dist/complex.d.ts +23 -0
- package/dist/complex.js +30 -0
- package/dist/computed-value.cjs +10 -0
- package/dist/computed-value.d.cts +8 -0
- package/dist/computed-value.d.ts +8 -0
- package/dist/computed-value.js +10 -0
- package/dist/derived-patterns.cjs +94 -0
- package/dist/derived-patterns.d.cts +7 -0
- package/dist/derived-patterns.d.ts +7 -0
- package/dist/derived-patterns.js +91 -0
- package/dist/evaluator.cjs +113 -4
- package/dist/evaluator.js +113 -4
- package/dist/index.cjs +13 -0
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +4 -2
- package/dist/tree.cjs +31 -1
- package/dist/tree.d.cts +53 -3
- package/dist/tree.d.ts +53 -3
- package/dist/tree.js +28 -2
- package/package.json +1 -1
- package/schemas/trilean.schema.json +1 -1
package/README.md
CHANGED
|
@@ -188,8 +188,9 @@ These hold across every part of the design below, and any implementation change
|
|
|
188
188
|
|
|
189
189
|
- **No assumptions about consumer data.** The only places this package touches real data are three named resolver contracts (see [Resolvers](#resolvers)). The schema stores *what to pass* to a resolver, never any resolver logic itself, and never interprets the meaning of an opaque key, table identifier, or collection reference.
|
|
190
190
|
- **Three outcomes, never two.** Every evaluation produces a definite result or an indeterminate result carrying a reason — never a bare `boolean`/`number`, and never a thrown exception for a data-quality problem. See [The evaluation model](#the-evaluation-model).
|
|
191
|
-
- **Derived constructs are compositions, not new logic.** Anything describable as "some other primitive, wired together" is implemented that way, so its correctness is inherited rather than requiring separate proof. See [Derived connectives](#derived-connectives), [Derived aggregates](#derived-aggregates),
|
|
191
|
+
- **Derived constructs are compositions, not new logic.** Anything describable as "some other primitive, wired together" is implemented that way, so its correctness is inherited rather than requiring separate proof. See [Derived connectives](#derived-connectives), [Derived aggregates](#derived-aggregates), [Derived values](#derived-values), [Pattern-matching builders](#pattern-matching-builders), and [Defining your own named presets](#defining-your-own-named-presets).
|
|
192
192
|
- **One schema, mechanically derived artefacts.** A single canonical type definition produces the runtime validator and the portable wire-format schema; they cannot drift apart because there is only one source. See [Schema strategy](#schema-strategy).
|
|
193
|
+
- **A numeric extension that stays closed-form is in scope; a different kind of computation is not.** When something the current numeric model does not cover comes up, the test is whether evaluating it is still closed-form numeric evaluation — no solving, no simplification, no code execution. If it is, it belongs here, however unlike the existing kinds it looks: [Complex values](#complex-values) were once listed under [Out of scope](#out-of-scope) on a sizing judgement that turned out to be wrong, since complex arithmetic is exactly the closed-form evaluation this evaluator already does for every other kind. What stays behind [`delegate`](#delegate) is a genuinely different *kind* of computation — symbolic algebra, arbitrary external computation — not merely a kind of number the model has not reached yet.
|
|
193
194
|
- **Generic examples only.** Every example in this document uses invented, placeholder field names (`temperature`, `orderTotal`, `isActive`, `x`, `y`, `amount`, `items`) with no resemblance to any particular company, product, or industry's real data model.
|
|
194
195
|
|
|
195
196
|
## The evaluation model
|
|
@@ -367,12 +368,44 @@ The N-ary forms of `and`/`or`: given an ordered list of operands (rather than ex
|
|
|
367
368
|
|
|
368
369
|
### `compare`
|
|
369
370
|
|
|
370
|
-
A relational-comparison leaf: compares two computed values using `gt`/`gte`/`lt`/`lte`/`eq`/`neq`. **Both `left` and `right` are `ExpressionNode`** — either side may be a plain literal/reference or an arbitrary formula from the expression tree; the comparison is symmetric, and an implementation that only allows a formula on one side is incomplete. Valid operand kinds are `number` (matching units required — see [Units](#units)), `instant`, or `
|
|
371
|
+
A relational-comparison leaf: compares two computed values using `gt`/`gte`/`lt`/`lte`/`eq`/`neq`. **Both `left` and `right` are `ExpressionNode`** — either side may be a plain literal/reference or an arbitrary formula from the expression tree; the comparison is symmetric, and an implementation that only allows a formula on one side is incomplete. Valid operand kinds are `number` (matching units required — see [Units](#units)), `instant`, `duration`, or `boolean`, plus `complex` for `eq`/`neq` only (see [Complex values](#complex-values)); comparing across different computed-value kinds, or comparing two numbers with incompatible units, is `wrong-type`. `boolean` only supports `eq`/`neq` — there is no natural ordering for a truth value, so `gt`/`gte`/`lt`/`lte` are `wrong-type` for a `boolean` operand.
|
|
371
372
|
|
|
372
373
|
### `textCompare`
|
|
373
374
|
|
|
374
375
|
A text-matching leaf, symmetric in the same way as `compare`: both `left` and `right` are `ExpressionNode`, and either may be a literal or an arbitrary formula. `equals`/`notEquals` are exact string equality; `matches`/`notMatches` interpret `right` as a pattern (an ECMAScript-style regular expression) tested against `left`'s text. Both operands must resolve to the `text` computed-value kind; anything else is `wrong-type`. A "small fixed category" value (e.g. a status label) is simply a `text` computed value from this leaf's point of view — no separate category kind exists.
|
|
375
376
|
|
|
377
|
+
### Pattern-matching builders
|
|
378
|
+
|
|
379
|
+
`matches` already covers arbitrary pattern matching, but writing the regular expression by hand is where the common, narrower cases go wrong: getting the escape-then-convert ordering backwards either stops wildcards working or silently reinterprets a literal asterisk in real data as one. Three builder functions compile a pattern string into an ordinary `textCompare` node instead — never a new node kind, never an evaluator branch, exactly the same composition-not-new-logic treatment [Derived connectives](#derived-connectives), [Derived aggregates](#derived-aggregates), and [Derived values](#derived-values) already give `xor`/`sum`/`coalesce`:
|
|
380
|
+
|
|
381
|
+
```ts
|
|
382
|
+
const command: ExpressionNode = { kind: "reference", key: "command" };
|
|
383
|
+
const path: ExpressionNode = { kind: "reference", key: "path" };
|
|
384
|
+
|
|
385
|
+
// Matches "ls" and "ls -la", never "lsof".
|
|
386
|
+
prefixPattern(command, "ls");
|
|
387
|
+
// Matches "git add file" and, by the trailing-wildcard convenience below, bare "git".
|
|
388
|
+
wildcardPattern(command, "git *");
|
|
389
|
+
// Matches "workspace/report.txt", but not "workspace/archive/report.txt".
|
|
390
|
+
hierarchicalGlobPattern(path, "workspace/*");
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Each returns an ordinary predicate node — `prefixPattern(command, "ls")` is exactly `{ kind: "textCompare", op: "matches", left: command, right: { kind: "textLiteral", value: "^ls(?: [\\s\\S]*)?$" } }`. Compilation happens once, when the tree is built, so what is stored and serialised is a `textCompare` tree indistinguishable from one written out by hand — a consumer that never calls a builder loses nothing, and a serialised tree carries no dependency on the builder that produced it.
|
|
394
|
+
|
|
395
|
+
The three are separate dialects, deliberately not one function with a mode argument, because they answer different questions and mixing them silently changes what a pattern means:
|
|
396
|
+
|
|
397
|
+
| Builder | `*` | `**` | `?` | Escapes | Intended for |
|
|
398
|
+
|---|---|---|---|---|---|
|
|
399
|
+
| `prefixPattern` | literal | literal | literal | none — the prefix is a plain literal throughout | Command/label prefixes where `"ls"` must match `"ls"` and `"ls -la"` but never `"lsof"` |
|
|
400
|
+
| `wildcardPattern` | any characters | (two wildcards in a row) | literal | `\*` for a literal asterisk, `\\` for a literal backslash | Flat strings with no internal hierarchy |
|
|
401
|
+
| `hierarchicalGlobPattern` | any characters within one `/`-delimited segment | any characters across segments | one character within a segment | none — a backslash is a literal backslash | Path- or category-tree-shaped values |
|
|
402
|
+
|
|
403
|
+
Two behaviours in `wildcardPattern` are worth stating rather than leaving to be inferred. Its pattern is trimmed before compiling. And a pattern whose **only** unescaped wildcard is a trailing `" *"` also matches the bare prefix, so `"git *"` matches `"git"` as well as `"git add file"` — the convenience does not apply to `"git * *"`, where both wildcards are still required.
|
|
404
|
+
|
|
405
|
+
The compiled pattern is a fully anchored, flag-free string: "any character" is spelled `[\s\S]` rather than `.`, because the stored pattern carries no `s` flag and nothing downstream can add one, and the only characters escaped are ECMAScript's own `SyntaxCharacter` set plus `/`, which are exactly the escapes that stay valid under a `u`/`v`-flagged `RegExp` as well as an unflagged one. A compiled pattern is therefore portable in the strongest available sense — it means the same thing wherever it is compiled, including pasted verbatim into a `/.../` literal.
|
|
406
|
+
|
|
407
|
+
Three-valued behaviour is inherited unchanged from [`textCompare`](#textcompare) and needs no separate proof: an unresolvable subject is indeterminate rather than a non-match, and a non-`text` subject is `wrong-type` — a compiled pattern never turns a data problem into a definite `false`.
|
|
408
|
+
|
|
376
409
|
### `memberOf`
|
|
377
410
|
|
|
378
411
|
A membership-test leaf, parallel to `compare` and `textCompare` rather than folded into either one's operator set: `operand` is the `ExpressionNode` being tested; `candidates` is a list of `ExpressionNode`s to test it against, every element of which may independently be an arbitrary formula, not only a literal — the same symmetry principle already applied to `compare` and `textCompare`. `op: "in"` asks whether `operand` equals any candidate; `op: "notIn"` asks whether it equals none of them.
|
|
@@ -400,8 +433,10 @@ type DurationUnit = "ms" | "s" | "min" | "h" | "d";
|
|
|
400
433
|
type ComputedValue =
|
|
401
434
|
| { kind: "number"; value: number; unit?: Unit }
|
|
402
435
|
| { kind: "text"; value: string }
|
|
436
|
+
| { kind: "boolean"; value: boolean }
|
|
403
437
|
| { kind: "instant"; value: string } // ISO-8601 timestamp
|
|
404
|
-
| { kind: "duration"; value: number; unit: DurationUnit }
|
|
438
|
+
| { kind: "duration"; value: number; unit: DurationUnit }
|
|
439
|
+
| { kind: "complex"; re: number; im: number; unit?: Unit };
|
|
405
440
|
|
|
406
441
|
type ArithmeticOperator = "add" | "subtract" | "multiply" | "divide" | "power" | "modulo";
|
|
407
442
|
|
|
@@ -415,8 +450,11 @@ type HitPolicy = "first" | "unique";
|
|
|
415
450
|
type ExpressionNode =
|
|
416
451
|
| { kind: "numberLiteral"; value: number; unit?: Unit }
|
|
417
452
|
| { kind: "textLiteral"; value: string }
|
|
453
|
+
| { kind: "booleanLiteral"; value: boolean }
|
|
418
454
|
| { kind: "instantLiteral"; value: string }
|
|
419
455
|
| { kind: "durationLiteral"; value: number; unit: DurationUnit }
|
|
456
|
+
| { kind: "complexLiteral"; re: number; im: number; unit?: Unit } // rectangular
|
|
457
|
+
| { kind: "complexLiteral"; magnitude: number; phase: number; unit?: Unit } // polar -- see Complex values
|
|
420
458
|
| { kind: "reference"; key: JsonValue; unit?: Unit }
|
|
421
459
|
| { kind: "arithmetic"; op: ArithmeticOperator; left: ExpressionNode; right: ExpressionNode }
|
|
422
460
|
| { kind: "negate"; operand: ExpressionNode }
|
|
@@ -433,7 +471,7 @@ A `textLiteral` kind is included even though it is not separately enumerated as
|
|
|
433
471
|
|
|
434
472
|
### Literals
|
|
435
473
|
|
|
436
|
-
`numberLiteral`, `textLiteral`, `instantLiteral` (an ISO-8601 timestamp string),
|
|
474
|
+
`numberLiteral`, `textLiteral`, `booleanLiteral`, `instantLiteral` (an ISO-8601 timestamp string), `durationLiteral` (a magnitude plus a `DurationUnit`), and `complexLiteral` (either a real and an imaginary component, or a magnitude and a phase, plus an optional `Unit` — see [Complex values](#complex-values)) are always definite by construction — a literal node never itself produces an indeterminate outcome.
|
|
437
475
|
|
|
438
476
|
### `reference`
|
|
439
477
|
|
|
@@ -441,7 +479,7 @@ A reference to a single external value, identified by an opaque `key` whose mean
|
|
|
441
479
|
|
|
442
480
|
### `arithmetic`, `negate`
|
|
443
481
|
|
|
444
|
-
Binary arithmetic (`add`/`subtract`/`multiply`/`divide`/`power`/`modulo`) and unary negation, each over `number` computed values by default, with the temporal exceptions listed under [Temporal values](#temporal-values) below. `negate` is an explicit node — never sugar for "zero minus the value" — because it also applies to `duration` values (negating a duration reverses its direction) where "zero minus" has no natural literal-zero counterpart. Division by zero, or any operator given an operand outside its mathematical domain, is `domain-error`; a non-numeric, non-temporal operand where a number was required is `wrong-type`; any operand that is itself indeterminate makes the whole node indeterminate, with no rescuing value on the other side (see [Three-valued propagation rules](#three-valued-propagation-rules)).
|
|
482
|
+
Binary arithmetic (`add`/`subtract`/`multiply`/`divide`/`power`/`modulo`) and unary negation, each over `number` computed values by default, with the temporal exceptions listed under [Temporal values](#temporal-values) and the complex ones under [Complex values](#complex-values) below. `negate` is an explicit node — never sugar for "zero minus the value" — because it also applies to `duration` values (negating a duration reverses its direction) where "zero minus" has no natural literal-zero counterpart; over a `complex` value it flips both components. Division by zero, or any operator given an operand outside its mathematical domain, is `domain-error`; a non-numeric, non-temporal operand where a number was required is `wrong-type`; any operand that is itself indeterminate makes the whole node indeterminate, with no rescuing value on the other side (see [Three-valued propagation rules](#three-valued-propagation-rules)).
|
|
445
483
|
|
|
446
484
|
### `call`
|
|
447
485
|
|
|
@@ -449,7 +487,7 @@ A named function applied to an ordered list of `ExpressionNode` arguments. The s
|
|
|
449
487
|
|
|
450
488
|
### Units
|
|
451
489
|
|
|
452
|
-
`numberLiteral` and `reference` may carry a `unit`, represented as a dimensional-exponent map (e.g. `{ m: 1, s: -1 }` for metres per second) rather than an opaque string, so that unit combination follows real dimensional analysis instead of string matching. A bare symbol like `"kg"` is shorthand for `{ kg: 1 }`.
|
|
490
|
+
`numberLiteral`, `complexLiteral`, and `reference` may carry a `unit`, represented as a dimensional-exponent map (e.g. `{ m: 1, s: -1 }` for metres per second) rather than an opaque string, so that unit combination follows real dimensional analysis instead of string matching. A bare symbol like `"kg"` is shorthand for `{ kg: 1 }`.
|
|
453
491
|
|
|
454
492
|
- `add`/`subtract` between two unit-tagged numbers require **identical** dimensional-exponent maps. A mismatch is `wrong-type` ("incompatible units") — units are never silently coerced or dropped.
|
|
455
493
|
- `multiply`/`divide` combine the two operands' unit maps by dimensional analysis: multiplying adds exponents per dimension, dividing subtracts them. An operand with no `unit` is treated as dimensionless (an empty map) for this purpose.
|
|
@@ -463,6 +501,53 @@ A named function applied to an ordered list of `ExpressionNode` arguments. The s
|
|
|
463
501
|
|
|
464
502
|
Any other arithmetic combination touching an `instant` or `duration` (adding two instants, multiplying a duration by an instant, comparing an instant against a plain number, and so on) is `wrong-type`. A reference implementation normalises `duration` values to a single base unit (milliseconds) internally before combining two durations of different `DurationUnit`s, then reports the result in whichever unit the node's own context calls for.
|
|
465
503
|
|
|
504
|
+
### Complex values
|
|
505
|
+
|
|
506
|
+
`complex` is a computed-value kind alongside `number`, for the domains — signal processing, control theory, anything phasor-shaped — where a formula naturally mixes real and complex terms in one expression. It stays inside this evaluator rather than behind [`delegate`](#delegate) because it is closed-form numeric evaluation, exactly what every other kind here already does; see [Design principles](#design-principles) for that scope test in general.
|
|
507
|
+
|
|
508
|
+
**One canonical representation, rectangular.** A `complex` value is stored as `{ re, im }` and never as a magnitude and a phase, and there is deliberately no `form` discriminant offering both. Three reasons, in order of weight:
|
|
509
|
+
|
|
510
|
+
1. **A second form would make equality ambiguous.** Polar coordinates do not encode a value uniquely — phase is only defined modulo a full turn, and a zero-magnitude value has no meaningful phase at all — so the same complex number would have unboundedly many polar encodings. `eq` and `memberOf` are exact equality throughout this design (see [`compare`](#compare)); making them work across two forms would mean either normalising on every comparison or introducing an approximate equality for this one kind, and neither belongs in a design where every other kind compares exactly.
|
|
511
|
+
2. **A discriminant would double the branching in every operator** — quadruple it for a binary one — for a choice that changes no value. Every operator would still convert to rectangular internally, because that is where the closed forms live, so the discriminant would buy nothing at evaluation time and cost at every boundary.
|
|
512
|
+
3. **Rectangular is what the operators actually need.** `add`/`subtract` are component-wise in it; `multiply`, `divide`, `negate`, and integer `power` all have standard closed forms in it. Polar's advantage — multiplication and division as one product of magnitudes and one sum of angles — does not extend to addition at all, which would have to convert back and forth.
|
|
513
|
+
|
|
514
|
+
The magnitude-and-phase view stays reachable through four exported conversion helpers rather than a second encoding: `complexFromPolar(magnitude, phase, unit?)` and `complexLiteralFromPolar(magnitude, phase, unit?)` build a value or a literal node from polar terms, and `complexMagnitude(value)` and `complexPhase(value)` read them back out — the magnitude as a real number in the value's own unit, the phase as a dimensionless real number of radians. Conversions at the edges, one representation in the middle.
|
|
515
|
+
|
|
516
|
+
**The wire-format literal accepts either authoring form, structurally discriminated.** `ComputedValue`'s own `complex` kind stays exactly the single rectangular shape described above — nothing about it changes. But the `complexLiteral` *node* is a plain union of two shapes, `{ kind: "complexLiteral", re, im, unit? }` and `{ kind: "complexLiteral", magnitude, phase, unit? }`, told apart by which fields are present rather than by a `form` tag, since both still share the one literal `kind`. This is not a second encoding of `ComputedValue` reappearing through the back door — it exists only at the authoring boundary, for whichever of the two forms is natural for a given domain to write directly into JSON rather than hand-computing a conversion before ever constructing the tree, and the evaluator normalises whichever form was used to the single rectangular `ComputedValue` immediately, before any arithmetic, comparison, or negation ever runs. A rectangular literal and a polar literal representing the same underlying number are therefore indistinguishable from that point on: they evaluate to the identical `ComputedValue` and compare `eq` to one another exactly as two rectangular literals with the same components would.
|
|
517
|
+
|
|
518
|
+
**Arithmetic.**
|
|
519
|
+
|
|
520
|
+
- `add`/`subtract` are component-wise, requiring **identical** dimensional-exponent maps exactly as real numbers do (see [Units](#units)).
|
|
521
|
+
- `multiply`/`divide` are real complex multiplication and division — `(a + bi)(c + di) = (ac − bd) + (ad + bc)i`, and the corresponding quotient — never component-wise. Units combine by the same dimensional analysis real numbers use. A zero divisor means both components zero; a divisor with only a zero real part divides perfectly well.
|
|
522
|
+
- `power` is defined for a **real integer exponent** and evaluated as the repeated multiplication that integer exponentiation is, with a negative exponent the reciprocal of the positive one. Like a real `power`, it requires dimensionless operands. An arbitrary complex exponent is a genuinely bigger question — it needs the complex logarithm, which is multivalued, so it needs a branch-cut convention this design has not chosen — and is deliberately out of scope for now: it is `wrong-type`, as is a non-integer real exponent, on the same reading of that code used throughout ("an answer exists, but this operator does not accept this operand" — compare `power`'s existing dimensionless-operands requirement, also `wrong-type`).
|
|
523
|
+
- `modulo` is `domain-error`, not `wrong-type`: a remainder needs a canonical notion of how many whole divisors fit, and the complex plane has no ordering to supply one. There is no answer to accept, which is the same category as division by zero.
|
|
524
|
+
|
|
525
|
+
**A real operand is promoted, never rejected.** Mixing a `number` with a `complex` in one `arithmetic` node works: every real number *is* a complex number with a zero imaginary part, so the promotion is exact, total, and canonical — unlike the temporal cross-kind combinations above, which had to be enumerated one by one precisely because no such embedding exists between an `instant` and a `duration`. Scaling a complex value by a real one, or offsetting it by a real constant, is the common case, and forcing every real literal in such a formula to be rewritten as a complex one would defeat the point. The result is `complex` whenever either operand is, even when the imaginary part comes out zero: a node's result kind follows its operand kinds, never the values that happen to flow through it.
|
|
526
|
+
|
|
527
|
+
**Comparison is kind-strict, deliberately unlike arithmetic.** `gt`/`gte`/`lt`/`lte` are `wrong-type` for a `complex` operand — the complex plane carries no total order — exactly as they already are for `text`. `eq`/`neq` work normally, as exact equality across both components under the same unit-compatibility rule numbers already have, and `memberOf` matches the same way. But a `complex` compared against a `number` is `wrong-type`, with no promotion: arithmetic *produces* a value, so promoting a real operand loses nothing, whereas a comparison *consumes* two, and this design already treats a kind difference between them as a modelling error worth surfacing — the same reason an `instant` is never compared against a plain `number` despite being a count of milliseconds underneath.
|
|
528
|
+
|
|
529
|
+
Ordering a complex quantity therefore goes through whichever real projection the formula actually means — most often its magnitude. This package ships no built-in function set (see [`call`](#call)), so that bridge is an ordinary registry entry, one line over the exported helper:
|
|
530
|
+
|
|
531
|
+
```ts
|
|
532
|
+
const functions: FunctionRegistry = {
|
|
533
|
+
magnitude: (args) =>
|
|
534
|
+
args[0]?.kind === "complex"
|
|
535
|
+
? complexMagnitude(args[0])
|
|
536
|
+
: { domainError: "expected a complex argument" },
|
|
537
|
+
};
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
which a tree then calls like any other function, putting a real number back on the left of an ordinary `compare`:
|
|
541
|
+
|
|
542
|
+
```json
|
|
543
|
+
{
|
|
544
|
+
"kind": "compare",
|
|
545
|
+
"op": "gt",
|
|
546
|
+
"left": { "kind": "call", "fn": "magnitude", "args": [{ "kind": "reference", "key": "x" }] },
|
|
547
|
+
"right": { "kind": "numberLiteral", "value": 13 }
|
|
548
|
+
}
|
|
549
|
+
```
|
|
550
|
+
|
|
466
551
|
### `lookup`
|
|
467
552
|
|
|
468
553
|
Resolves a single value from a named external table-like source, keyed by one or more `ExpressionNode` keys, via resolver 2 (see [Resolvers](#resolvers)). The schema never interprets what "table" or "key" mean to a given consumer; `table` and the resolved key values are passed through verbatim. If any key expression is itself indeterminate, the lookup is indeterminate with that reason (no key evaluation, no lookup attempt). If the resolver reports no match, the result is `not-found`.
|
|
@@ -547,7 +632,7 @@ const average = (collection: JsonValue, item: ExpressionNode, filter?: Predicate
|
|
|
547
632
|
|
|
548
633
|
`sum` needs no per-item probe beyond `item` itself: it is a literal `reduce` seeded at `0`, adding each participating item's projected value to the running total, and it already goes indeterminate if `item` fails to resolve for any participating item — no separate mechanism needed, since `item`'s value is exactly what gets added.
|
|
549
634
|
|
|
550
|
-
`count` takes an optional third argument, `probe`, and this is where it matters that `filter` and a probe are not the same thing. `filter` *excludes* an item from participating — a filtered-out item's absence is invisible in the final result, exactly as if it had never been in the collection at all. A `probe` does the opposite: it doesn't decide whether an item participates, it makes the *whole count* indeterminate if it fails to resolve for *any* participating item, surfacing "I cannot give you a trustworthy count" rather than silently reporting a smaller, technically-successful count for the same underlying data-quality problem — precisely the distinction the rest of this document's indeterminate-outcome model exists to preserve (see [The evaluation model](#the-evaluation-model)). `count(collection, filter)` with no `probe` is a plain `reduce` seeded at `0` that adds `1` per participating item, with no indeterminacy of its own beyond `filter`'s. `count(collection, filter, probe)` instead adds `presenceOf(probe)` per participating item — a small helper built entirely from already-established primitives, with no restriction on `probe`'s kind: it tests `probe` for membership in the single-element list `[probe]`, so a `memberOf` "in" test against itself is trivially true whenever `probe` resolves to a definite value of *any* kind (`memberOf`'s equality is already kind-agnostic across `number`/`text`/`instant`/`duration` — see [`memberOf`](#memberof)), and exactly `probe`'s own indeterminate outcome otherwise, per `memberOf`'s own "evaluate `operand` first" rule. A `conditional` then turns that boolean into the number `1`; its `fallback` is never reached, since a definite `probe` always equals itself. (A real implementation may memoise `probe`'s single evaluation rather than running the resolver twice for `operand` and its one `candidates` entry — resolvers are pure functions of their inputs throughout this design, so this is a performance choice, not a correctness one.)
|
|
635
|
+
`count` takes an optional third argument, `probe`, and this is where it matters that `filter` and a probe are not the same thing. `filter` *excludes* an item from participating — a filtered-out item's absence is invisible in the final result, exactly as if it had never been in the collection at all. A `probe` does the opposite: it doesn't decide whether an item participates, it makes the *whole count* indeterminate if it fails to resolve for *any* participating item, surfacing "I cannot give you a trustworthy count" rather than silently reporting a smaller, technically-successful count for the same underlying data-quality problem — precisely the distinction the rest of this document's indeterminate-outcome model exists to preserve (see [The evaluation model](#the-evaluation-model)). `count(collection, filter)` with no `probe` is a plain `reduce` seeded at `0` that adds `1` per participating item, with no indeterminacy of its own beyond `filter`'s. `count(collection, filter, probe)` instead adds `presenceOf(probe)` per participating item — a small helper built entirely from already-established primitives, with no restriction on `probe`'s kind: it tests `probe` for membership in the single-element list `[probe]`, so a `memberOf` "in" test against itself is trivially true whenever `probe` resolves to a definite value of *any* kind (`memberOf`'s equality is already kind-agnostic across `number`/`text`/`boolean`/`instant`/`duration` — see [`memberOf`](#memberof)), and exactly `probe`'s own indeterminate outcome otherwise, per `memberOf`'s own "evaluate `operand` first" rule. A `conditional` then turns that boolean into the number `1`; its `fallback` is never reached, since a definite `probe` always equals itself. (A real implementation may memoise `probe`'s single evaluation rather than running the resolver twice for `operand` and its one `candidates` entry — resolvers are pure functions of their inputs throughout this design, so this is a performance choice, not a correctness one.)
|
|
551
636
|
|
|
552
637
|
`average` is `sum` divided by `count` over the same `collection`/`filter`, with no `probe` — `sum`'s own `item` already forces every participating item's projected value to resolve, so `average`'s numerator is already indeterminate under exactly the condition a `count` probe exists to detect, with nothing left to duplicate. Nothing new to verify for the empty-collection case either: division's own already-established rule (zero divisor is `domain-error`) is *why* `average` over an empty collection is `domain-error`, since `count` over an empty collection is `0` and `sum(...)/0` already means exactly that.
|
|
553
638
|
|
|
@@ -585,6 +670,29 @@ Falling through to the next candidate therefore happens only on `exists`'s own `
|
|
|
585
670
|
|
|
586
671
|
A real implementation may memoise a candidate's single evaluation rather than running its resolver twice — once for the `exists` probe, once again for `then` — exactly the same performance caveat [Derived aggregates](#derived-aggregates)'s `presenceOf` already documents for its own `memberOf` probe; resolvers are pure functions of their inputs throughout this design, so this is a performance choice, not a correctness one.
|
|
587
672
|
|
|
673
|
+
### Defining your own named presets
|
|
674
|
+
|
|
675
|
+
This is exactly the same composition-not-new-logic treatment already given to `xor`/`sum`/`coalesce` above — nothing stops application code from defining its own named builder functions the same way, for whatever domain-specific composed queries come up repeatedly in a given consumer's own rules.
|
|
676
|
+
|
|
677
|
+
```ts
|
|
678
|
+
/** isRecentlyActive(30) reads as "the item's lastActiveAt instant is within the last 30 days" — a small, named composition over compare/arithmetic, exactly the same "assembles ordinary nodes" treatment sum/coalesce already get above. Built as `now + (-days)` rather than `now - days`: per "Temporal values" above, `instant - duration` is not a defined cross-kind combination, only `instant + duration` is, so negating the duration first is how this reaches the same "days ago" instant using only defined operators. */
|
|
679
|
+
const isRecentlyActive = (days: number): PredicateNode => ({
|
|
680
|
+
kind: "compare",
|
|
681
|
+
op: "gt",
|
|
682
|
+
left: { kind: "reference", key: "lastActiveAt" },
|
|
683
|
+
right: {
|
|
684
|
+
kind: "arithmetic",
|
|
685
|
+
op: "add",
|
|
686
|
+
left: { kind: "reference", key: "now" },
|
|
687
|
+
right: { kind: "negate", operand: { kind: "durationLiteral", value: days, unit: "d" } },
|
|
688
|
+
},
|
|
689
|
+
});
|
|
690
|
+
```
|
|
691
|
+
|
|
692
|
+
A UI surfacing these to an end user treats each one as a named preset in a node-picker — a label ("Recently active") plus whatever parameters the builder function takes (`days`) — and splices the expanded tree in at the point the user picked it, exactly as if they'd hand-built that subtree themselves; nothing about the resulting PredicateNode/ExpressionNode distinguishes a preset-sourced subtree from a manually-authored one.
|
|
693
|
+
|
|
694
|
+
This is the "bake in at authoring time" half of the picture: a preset's own definition lives in application code, expanded once, at the moment a user picks it, into an ordinary static subtree. [`treeReference`](#treereference) is the complementary half — a *live*, centrally-editable reference, resolved fresh on every evaluation rather than expanded once at authoring time. Choosing between them is exactly the choice between "this composition is fixed application logic" (a named preset, this section) and "this composition is itself data someone should be able to edit without a deploy" (a treeReference).
|
|
695
|
+
|
|
588
696
|
### `delegate`
|
|
589
697
|
|
|
590
698
|
An explicitly-named external system plus an arbitrary, unevaluated JSON payload, standing in for the whole node without this package attempting to evaluate it itself — see [Out of scope](#out-of-scope). Evaluating a `delegate` node is not part of this package's own evaluation semantics. The reference evaluator accepts an optional delegate handler per external system name; if none is registered for the named `system`, evaluating the node is indeterminate (`wrong-type`, "no delegate handler registered for external system '<name>'"). Consumers who want a `delegate` node to actually resolve are expected either to register a handler, or to pre-process the tree — walk it, find delegation nodes, invoke the named external system out of band, and substitute the result as a literal — before the tree ever reaches this package's evaluator.
|
|
@@ -713,15 +821,15 @@ How each reason category can arise, per node kind. "Propagates" means: an indete
|
|
|
713
821
|
| `and` | propagates, **unless** the other operand is definitely `false` (absorbs) | as `not-found` | as `not-found` |
|
|
714
822
|
| `or` | propagates, **unless** the other operand is definitely `true` (absorbs) | as `not-found` | as `not-found` |
|
|
715
823
|
| `allOf` / `anyOf` | as `and`/`or`, extended pairwise across the list | as `and`/`or` | as `and`/`or` |
|
|
716
|
-
| `compare` | either operand not found | operand kinds differ, or units incompatible, or kind is not `number`/`instant`/`duration` | never directly (comparison itself has no domain restriction) |
|
|
824
|
+
| `compare` | either operand not found | operand kinds differ, or units incompatible, or kind is not `number`/`instant`/`duration`/`complex`, or an ordering operator was given a `complex` operand (see [Complex values](#complex-values)) | never directly (comparison itself has no domain restriction) |
|
|
717
825
|
| `textCompare` | either operand not found | either operand is not `text` | never directly |
|
|
718
826
|
| `memberOf` | `operand` not found, or (with no definite match found) a scanned candidate not found | `operand`/a candidate resolves to an incompatible kind or unit, with no definite match found among the rest | never directly |
|
|
719
827
|
| `exists` | never — converts operand `not-found` to definite `false` | never — converts operand `wrong-type`/`domain-error` to definite `true` | never — see `wrong-type` column |
|
|
720
828
|
| `some` / `every` | an item's `filter` or `item` sub-node reports not-found, and it is not absorbed by an already-decided item | as `not-found` | as `not-found` |
|
|
721
|
-
| literals (`numberLiteral`, `textLiteral`, `instantLiteral`, `durationLiteral`) | never | never | never |
|
|
829
|
+
| literals (`numberLiteral`, `textLiteral`, `instantLiteral`, `durationLiteral`, `complexLiteral`) | never | never | never |
|
|
722
830
|
| `reference` | resolver reports absence | resolver's value doesn't match an expected `unit`, or is used where an incompatible kind is required upstream | never directly |
|
|
723
|
-
| `arithmetic` | either operand not found | operand not numeric (or temporal-kind mismatch — see [Temporal values](#temporal-values)), or unit mismatch on add/subtract | zero divisor, or any other documented domain violation for the operator |
|
|
724
|
-
| `negate` | operand not found | operand not `number`/`duration` | never directly |
|
|
831
|
+
| `arithmetic` | either operand not found | operand not numeric (or temporal-kind mismatch — see [Temporal values](#temporal-values)), or unit mismatch on add/subtract, or a `power` exponent that is not a real integer over a `complex` operand (see [Complex values](#complex-values)) | zero divisor, `modulo` over a `complex` operand, or any other documented domain violation for the operator |
|
|
832
|
+
| `negate` | operand not found | operand not `number`/`duration`/`complex` | never directly |
|
|
725
833
|
| `call` | any argument not found | unregistered function name, or an argument of the wrong kind for that function | argument outside the function's valid domain (e.g. negative input to `squareRoot`) |
|
|
726
834
|
| `lookup` | any key not found, or resolver reports no match | a key expression resolves to the wrong kind for that table | never directly |
|
|
727
835
|
| `conditional` | `"first"`: an unmatched guard's own evaluation is `not-found`, before any earlier guard matched.<br>`"unique"`: any case's `when` is `not-found`, unless 2+ cases already definitely matched (see `domain-error`, which then takes priority).<br>Both: also the chosen branch's (`then`/`fallback`) own result if it is `not-found`. | Same pattern as `not-found`, substituting `wrong-type` throughout (guard evaluation and chosen branch alike). | `"unique"` only: 2+ cases are definitely `true` — see [`conditional`](#conditional)'s absorption order.<br>Both: same pattern as `not-found`, substituting `domain-error` (guard evaluation and chosen branch alike). |
|
|
@@ -734,7 +842,7 @@ How each reason category can arise, per node kind. "Propagates" means: an indete
|
|
|
734
842
|
|
|
735
843
|
A single condition combining a boolean tree, a comparison leaf whose value side is itself a formula, a fold/aggregation node, and all three resolver contracts in use — every name below is a generic placeholder.
|
|
736
844
|
|
|
737
|
-
**Rule:** "`isActive` is true, and the sum of `amount` across the `items` collection is greater than `x + y`." `isActive` is
|
|
845
|
+
**Rule:** "`isActive` is true, and the sum of `amount` across the `items` collection is greater than `x + y`." `isActive` is a `boolean` computed value, compared for equality against the literal `true`. The `fold` below is exactly what the [`sum`](#derived-aggregates) builder produces — shown here as the literal tree it assembles, to keep the resolver trace below concrete.
|
|
738
846
|
|
|
739
847
|
```json
|
|
740
848
|
{
|
|
@@ -743,7 +851,7 @@ A single condition combining a boolean tree, a comparison leaf whose value side
|
|
|
743
851
|
"kind": "compare",
|
|
744
852
|
"op": "eq",
|
|
745
853
|
"left": { "kind": "reference", "key": "isActive" },
|
|
746
|
-
"right": { "kind": "
|
|
854
|
+
"right": { "kind": "booleanLiteral", "value": true }
|
|
747
855
|
},
|
|
748
856
|
"right": {
|
|
749
857
|
"kind": "compare",
|
|
@@ -776,7 +884,7 @@ A minimal set of resolvers backing this against a plain in-memory record:
|
|
|
776
884
|
|
|
777
885
|
```ts
|
|
778
886
|
const data = {
|
|
779
|
-
isActive:
|
|
887
|
+
isActive: true,
|
|
780
888
|
x: 10,
|
|
781
889
|
y: 5,
|
|
782
890
|
items: [{ amount: 8 }, { amount: 12 }, { amount: 1 }],
|
|
@@ -786,7 +894,9 @@ const resolvers: Resolvers = {
|
|
|
786
894
|
async resolveValue(key, context) {
|
|
787
895
|
const record = context as Record<string, unknown>;
|
|
788
896
|
if (typeof key !== "string" || !(key in record)) return { found: false };
|
|
789
|
-
|
|
897
|
+
const value = record[key];
|
|
898
|
+
if (typeof value === "boolean") return { found: true, value: { kind: "boolean", value } };
|
|
899
|
+
return { found: true, value: { kind: "number", value: value as number } };
|
|
790
900
|
},
|
|
791
901
|
async resolveLookup() {
|
|
792
902
|
return { found: false }; // unused by this example
|
|
@@ -800,7 +910,7 @@ const resolvers: Resolvers = {
|
|
|
800
910
|
|
|
801
911
|
Tracing the evaluation against `data` as the root `EvaluationContext`:
|
|
802
912
|
|
|
803
|
-
1. `compare eq` (left branch): `resolveValue("isActive", data)` → `{ found: true, value: { kind: "
|
|
913
|
+
1. `compare eq` (left branch): `resolveValue("isActive", data)` → `{ found: true, value: { kind: "boolean", value: true } }`; compared against `booleanLiteral true` → definite `true`.
|
|
804
914
|
2. `fold` (`reduce`, seeded at `0`): `resolveCollection("items", data)` → three items. The accumulator starts at `0`; for each item in turn, `combine` evaluates `accumulator + reference("amount")` with that single item as context — `resolveValue("amount", item)` → `8`, `12`, `1`, all definite — stepping the accumulator `0 → 8 → 20 → 21`. Final accumulator → `21`.
|
|
805
915
|
3. `arithmetic add`: `resolveValue("x", data)` → `10`; `resolveValue("y", data)` → `5`. Sum → `15`.
|
|
806
916
|
4. `compare gt` (right branch): `21 > 15` → definite `true`.
|
|
@@ -815,10 +925,11 @@ Two variations show the propagation rules in action without changing the tree at
|
|
|
815
925
|
This package is a representation-plus-evaluator for conditions and formulas over already-available (or resolver-obtained) data. It deliberately does not include:
|
|
816
926
|
|
|
817
927
|
- **Symbolic algebra.** It cannot solve an expression for an unknown quantity, symbolically simplify an expression, or perform symbolic differentiation or integration. A consumer needing any of that is expected to translate the pure-arithmetic portion of an expression tree into the input format of existing, general-purpose symbolic-mathematics software — several mature, freely available options already exist — and let that external system do the symbolic work. This package's job stops at representing and numerically evaluating a tree, not manipulating it symbolically.
|
|
818
|
-
- **
|
|
819
|
-
|
|
928
|
+
- **Batch unresolvable-reference reporting.** This design deliberately has no node kind for asking "which of these references, across a whole batch, are unresolvable" as a single evaluation — only the [`exists`](#exists) leaf's one-at-a-time true/false/false-on-absence check. A tool that wants to report a *list* of every missing reference (for an authoring UI validating a tree before it's saved, say) is expected to build that on top of `exists` — walk the references of interest and evaluate an `exists` leaf over each — at the authoring/tooling layer, rather than this package growing a bespoke aggregate-diagnostic node kind for it. This is a deliberate boundary, not an oversight: it keeps the evaluation tree itself limited to producing one `Evaluation` per node, and leaves "collect many such results and report on them together" to whatever sits above the evaluator, exactly like symbolic algebra above is left to whatever sits beside it.
|
|
929
|
+
|
|
930
|
+
This package does not name or depend on any specific external tool for the delegation case above — it only defines the shape of the hand-off (an opaque payload plus a named destination system).
|
|
820
931
|
|
|
821
|
-
|
|
932
|
+
Complex-number and phasor arithmetic used to be listed here too, delegated out on the reasoning that supporting them would be a far larger and more invasive change than adding one more named function. That sizing was wrong: unlike symbolic algebra, which is a genuinely different kind of system, complex arithmetic is closed-form numeric evaluation, exactly what this evaluator already does for every other computed-value kind. It is now part of the core numeric model — see [Complex values](#complex-values), and [Design principles](#design-principles) for the scope test that judgement is now written down as.
|
|
822
933
|
|
|
823
934
|
## Prior art
|
|
824
935
|
|
package/dist/complex.cjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/complex.ts
|
|
3
|
+
const complexFromPolar = (magnitude, phase, unit) => ({
|
|
4
|
+
kind: "complex",
|
|
5
|
+
re: magnitude * Math.cos(phase),
|
|
6
|
+
im: magnitude * Math.sin(phase),
|
|
7
|
+
unit
|
|
8
|
+
});
|
|
9
|
+
/** The `complexLiteral` node counterpart of `complexFromPolar`, for authoring a tree in polar terms; the conversion itself is done once, there, rather than repeated here. */
|
|
10
|
+
const complexLiteralFromPolar = (magnitude, phase, unit) => {
|
|
11
|
+
const { re, im } = complexFromPolar(magnitude, phase, unit);
|
|
12
|
+
return {
|
|
13
|
+
kind: "complexLiteral",
|
|
14
|
+
re,
|
|
15
|
+
im,
|
|
16
|
+
unit
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
/** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
|
|
20
|
+
const complexMagnitude = (value) => ({
|
|
21
|
+
kind: "number",
|
|
22
|
+
value: Math.hypot(value.re, value.im),
|
|
23
|
+
unit: value.unit
|
|
24
|
+
});
|
|
25
|
+
/** arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. */
|
|
26
|
+
const complexPhase = (value) => ({
|
|
27
|
+
kind: "number",
|
|
28
|
+
value: Math.atan2(value.im, value.re)
|
|
29
|
+
});
|
|
30
|
+
//#endregion
|
|
31
|
+
exports.complexFromPolar = complexFromPolar;
|
|
32
|
+
exports.complexLiteralFromPolar = complexLiteralFromPolar;
|
|
33
|
+
exports.complexMagnitude = complexMagnitude;
|
|
34
|
+
exports.complexPhase = complexPhase;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ComputedValue, Unit } from "./computed-value.cjs";
|
|
2
|
+
import { ComplexLiteralNode } from "./tree.cjs";
|
|
3
|
+
//#region src/complex.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The `complex` computed-value kind stores one canonical representation, rectangular (`re` + `im`i), with no `form` discriminant offering a polar alternative alongside it -- see the "Complex values" section of README.md for the reasoning. These four helpers are what keep the magnitude-and-phase view reachable for the domains that reason that way, as conversions at the edges rather than a second encoding of the same value that every operator would then have to branch on.
|
|
6
|
+
*
|
|
7
|
+
* Phase is in radians throughout, measured from the positive real axis, matching `Math.atan2`'s own range of (-pi, pi].
|
|
8
|
+
*/
|
|
9
|
+
type ComplexValue = Extract<ComputedValue, {
|
|
10
|
+
kind: "complex";
|
|
11
|
+
}>;
|
|
12
|
+
type NumberValue = Extract<ComputedValue, {
|
|
13
|
+
kind: "number";
|
|
14
|
+
}>;
|
|
15
|
+
declare const complexFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexValue;
|
|
16
|
+
/** The `complexLiteral` node counterpart of `complexFromPolar`, for authoring a tree in polar terms; the conversion itself is done once, there, rather than repeated here. */
|
|
17
|
+
declare const complexLiteralFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexLiteralNode;
|
|
18
|
+
/** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
|
|
19
|
+
declare const complexMagnitude: (value: ComplexValue) => NumberValue;
|
|
20
|
+
/** arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. */
|
|
21
|
+
declare const complexPhase: (value: ComplexValue) => NumberValue;
|
|
22
|
+
//#endregion
|
|
23
|
+
export { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ComputedValue, Unit } from "./computed-value.js";
|
|
2
|
+
import { ComplexLiteralNode } from "./tree.js";
|
|
3
|
+
//#region src/complex.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The `complex` computed-value kind stores one canonical representation, rectangular (`re` + `im`i), with no `form` discriminant offering a polar alternative alongside it -- see the "Complex values" section of README.md for the reasoning. These four helpers are what keep the magnitude-and-phase view reachable for the domains that reason that way, as conversions at the edges rather than a second encoding of the same value that every operator would then have to branch on.
|
|
6
|
+
*
|
|
7
|
+
* Phase is in radians throughout, measured from the positive real axis, matching `Math.atan2`'s own range of (-pi, pi].
|
|
8
|
+
*/
|
|
9
|
+
type ComplexValue = Extract<ComputedValue, {
|
|
10
|
+
kind: "complex";
|
|
11
|
+
}>;
|
|
12
|
+
type NumberValue = Extract<ComputedValue, {
|
|
13
|
+
kind: "number";
|
|
14
|
+
}>;
|
|
15
|
+
declare const complexFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexValue;
|
|
16
|
+
/** The `complexLiteral` node counterpart of `complexFromPolar`, for authoring a tree in polar terms; the conversion itself is done once, there, rather than repeated here. */
|
|
17
|
+
declare const complexLiteralFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexLiteralNode;
|
|
18
|
+
/** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
|
|
19
|
+
declare const complexMagnitude: (value: ComplexValue) => NumberValue;
|
|
20
|
+
/** arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. */
|
|
21
|
+
declare const complexPhase: (value: ComplexValue) => NumberValue;
|
|
22
|
+
//#endregion
|
|
23
|
+
export { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase };
|
package/dist/complex.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region src/complex.ts
|
|
2
|
+
const complexFromPolar = (magnitude, phase, unit) => ({
|
|
3
|
+
kind: "complex",
|
|
4
|
+
re: magnitude * Math.cos(phase),
|
|
5
|
+
im: magnitude * Math.sin(phase),
|
|
6
|
+
unit
|
|
7
|
+
});
|
|
8
|
+
/** The `complexLiteral` node counterpart of `complexFromPolar`, for authoring a tree in polar terms; the conversion itself is done once, there, rather than repeated here. */
|
|
9
|
+
const complexLiteralFromPolar = (magnitude, phase, unit) => {
|
|
10
|
+
const { re, im } = complexFromPolar(magnitude, phase, unit);
|
|
11
|
+
return {
|
|
12
|
+
kind: "complexLiteral",
|
|
13
|
+
re,
|
|
14
|
+
im,
|
|
15
|
+
unit
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
/** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
|
|
19
|
+
const complexMagnitude = (value) => ({
|
|
20
|
+
kind: "number",
|
|
21
|
+
value: Math.hypot(value.re, value.im),
|
|
22
|
+
unit: value.unit
|
|
23
|
+
});
|
|
24
|
+
/** arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. */
|
|
25
|
+
const complexPhase = (value) => ({
|
|
26
|
+
kind: "number",
|
|
27
|
+
value: Math.atan2(value.im, value.re)
|
|
28
|
+
});
|
|
29
|
+
//#endregion
|
|
30
|
+
export { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase };
|
package/dist/computed-value.cjs
CHANGED
|
@@ -20,6 +20,10 @@ const ComputedValueSchema = zod.z.discriminatedUnion("kind", [
|
|
|
20
20
|
kind: zod.z.literal("text"),
|
|
21
21
|
value: zod.z.string()
|
|
22
22
|
}),
|
|
23
|
+
zod.z.object({
|
|
24
|
+
kind: zod.z.literal("boolean"),
|
|
25
|
+
value: zod.z.boolean()
|
|
26
|
+
}),
|
|
23
27
|
zod.z.object({
|
|
24
28
|
kind: zod.z.literal("instant"),
|
|
25
29
|
value: zod.z.string()
|
|
@@ -28,6 +32,12 @@ const ComputedValueSchema = zod.z.discriminatedUnion("kind", [
|
|
|
28
32
|
kind: zod.z.literal("duration"),
|
|
29
33
|
value: zod.z.number(),
|
|
30
34
|
unit: DurationUnitSchema
|
|
35
|
+
}),
|
|
36
|
+
zod.z.object({
|
|
37
|
+
kind: zod.z.literal("complex"),
|
|
38
|
+
re: zod.z.number(),
|
|
39
|
+
im: zod.z.number(),
|
|
40
|
+
unit: UnitSchema.optional()
|
|
31
41
|
})
|
|
32
42
|
]);
|
|
33
43
|
/** Drops zero-exponent dimensions so that, e.g., dividing a unit by itself normalises to the same dimensionless `{}` as an absent unit -- without this, `{ m: 0 }` and `{}` would compare unequal despite representing the same dimension. */
|
|
@@ -18,6 +18,9 @@ declare const ComputedValueSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
18
18
|
}, z.core.$strip>, z.ZodObject<{
|
|
19
19
|
kind: z.ZodLiteral<"text">;
|
|
20
20
|
value: z.ZodString;
|
|
21
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
22
|
+
kind: z.ZodLiteral<"boolean">;
|
|
23
|
+
value: z.ZodBoolean;
|
|
21
24
|
}, z.core.$strip>, z.ZodObject<{
|
|
22
25
|
kind: z.ZodLiteral<"instant">;
|
|
23
26
|
value: z.ZodString;
|
|
@@ -31,6 +34,11 @@ declare const ComputedValueSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
31
34
|
h: "h";
|
|
32
35
|
d: "d";
|
|
33
36
|
}>;
|
|
37
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
38
|
+
kind: z.ZodLiteral<"complex">;
|
|
39
|
+
re: z.ZodNumber;
|
|
40
|
+
im: z.ZodNumber;
|
|
41
|
+
unit: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
34
42
|
}, z.core.$strip>], "kind">;
|
|
35
43
|
type ComputedValue = z.infer<typeof ComputedValueSchema>;
|
|
36
44
|
/** An operand with no `unit` is dimensionless (an empty map) for comparison purposes. */
|
package/dist/computed-value.d.ts
CHANGED
|
@@ -18,6 +18,9 @@ declare const ComputedValueSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
18
18
|
}, z.core.$strip>, z.ZodObject<{
|
|
19
19
|
kind: z.ZodLiteral<"text">;
|
|
20
20
|
value: z.ZodString;
|
|
21
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
22
|
+
kind: z.ZodLiteral<"boolean">;
|
|
23
|
+
value: z.ZodBoolean;
|
|
21
24
|
}, z.core.$strip>, z.ZodObject<{
|
|
22
25
|
kind: z.ZodLiteral<"instant">;
|
|
23
26
|
value: z.ZodString;
|
|
@@ -31,6 +34,11 @@ declare const ComputedValueSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
31
34
|
h: "h";
|
|
32
35
|
d: "d";
|
|
33
36
|
}>;
|
|
37
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
38
|
+
kind: z.ZodLiteral<"complex">;
|
|
39
|
+
re: z.ZodNumber;
|
|
40
|
+
im: z.ZodNumber;
|
|
41
|
+
unit: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
34
42
|
}, z.core.$strip>], "kind">;
|
|
35
43
|
type ComputedValue = z.infer<typeof ComputedValueSchema>;
|
|
36
44
|
/** An operand with no `unit` is dimensionless (an empty map) for comparison purposes. */
|
package/dist/computed-value.js
CHANGED
|
@@ -19,6 +19,10 @@ const ComputedValueSchema = z.discriminatedUnion("kind", [
|
|
|
19
19
|
kind: z.literal("text"),
|
|
20
20
|
value: z.string()
|
|
21
21
|
}),
|
|
22
|
+
z.object({
|
|
23
|
+
kind: z.literal("boolean"),
|
|
24
|
+
value: z.boolean()
|
|
25
|
+
}),
|
|
22
26
|
z.object({
|
|
23
27
|
kind: z.literal("instant"),
|
|
24
28
|
value: z.string()
|
|
@@ -27,6 +31,12 @@ const ComputedValueSchema = z.discriminatedUnion("kind", [
|
|
|
27
31
|
kind: z.literal("duration"),
|
|
28
32
|
value: z.number(),
|
|
29
33
|
unit: DurationUnitSchema
|
|
34
|
+
}),
|
|
35
|
+
z.object({
|
|
36
|
+
kind: z.literal("complex"),
|
|
37
|
+
re: z.number(),
|
|
38
|
+
im: z.number(),
|
|
39
|
+
unit: UnitSchema.optional()
|
|
30
40
|
})
|
|
31
41
|
]);
|
|
32
42
|
/** Drops zero-exponent dimensions so that, e.g., dividing a unit by itself normalises to the same dimensionless `{}` as an absent unit -- without this, `{ m: 0 }` and `{}` would compare unequal despite representing the same dimension. */
|