refactor: change onType to match and take only one pattern and result (#22)
All checks were successful
/ test (push) Successful in 17s

Pursuant to #12. Besides changing the name of onType to match, and only allowing one pattern and result in `match()`,
this PR also arranges that in place of an onType with lots of alternating PATTERN, VALUE, PATTERN, VALUE arguments, one now exports an _array_ of `match(PATTERN, VALUE)` items.

Doesn't quite fully resolve #12, because there is still the question of whether `match(...)` can be left out for a behavior that literally matches anything (current behavior), or whether `match(Passthru, behavior)` should be required for such cases.

Reviewed-on: #22
Co-authored-by: Glen Whitney <glen@studioinfinity.org>
Co-committed-by: Glen Whitney <glen@studioinfinity.org>
This commit is contained in:
Glen Whitney 2025-04-22 05:01:21 +00:00 committed by Glen Whitney
parent 491e207fad
commit 236f46c0c0
22 changed files with 147 additions and 135 deletions

View file

@ -1,5 +1,5 @@
import {Type} from '#core/Type.js'
import {onType} from '#core/helpers.js'
import {match} from '#core/helpers.js'
const isComplex = z => z && typeof z === 'object' && 're' in z && 'im' in z
@ -10,15 +10,17 @@ function complexSpecialize(ComponentType) {
const specTest = z => isComplex(z) && compTest(z.re) && compTest(z.im)
const typeName = `Complex(${ComponentType})`
if (ComponentType.concrete) {
const fromSpec = [
ComponentType, math => r => ({re: r, im: ComponentType.zero})]
for (const [matchType, fctry] of ComponentType.from.patterns) {
fromSpec.push(this.specialize(matchType.type), math => {
const compConv = fctry(math)
return z => ({re: compConv(z.re), im: compConv(z.im)})
})
const fromSpec = [match(
ComponentType, math => r => ({re: r, im: ComponentType.zero}))]
for (const {pattern, does} of ComponentType.from) {
fromSpec.push(match(
this.specialize(pattern.type),
math => {
const compConv = does(math)
return z => ({re: compConv(z.re), im: compConv(z.im)})
}))
}
const typeOptions = {from: onType(...fromSpec), typeName}
const typeOptions = {from: fromSpec, typeName}
if ('zero' in ComponentType) {
typeOptions.zero = {re: ComponentType.zero, im: ComponentType.zero}
if ('one' in ComponentType) {