nicer pattern matching

This commit is contained in:
Joeri Exelmans 2025-06-17 11:12:34 +02:00
parent d5821c9cb9
commit 794cd3f120
2 changed files with 30 additions and 0 deletions

View file

@ -1,4 +1,5 @@
import { compareStrings } from "../compare/primitives.js";
import { unit } from "../primitives/unit.js";
import { capitalizeFirstLetter } from "../util/util.js";
const eatParameters = (numParams, result) => {
@ -33,6 +34,24 @@ const matchFn = (enumm, variantNames) => {
};
};
export const symbolElse = Symbol('else');
export const makeNiceMatchFn = (variantNames) => handlers => enumm => {
const incomplete = variantNames.filter(({l: variant}) => !handlers.hasOwnProperty(variant)).length > 0;
if (incomplete && !handlers.hasOwnProperty(symbolElse)) {
throw new Error("if not every variant is handled, must have 'else' handler");
}
if (!incomplete && handlers.hasOwnProperty(symbolElse)) {
console.warn("'else' handler will never be invoked because every variant is already handled");
}
for (const [variant, handler] of Object.entries(handlers)) {
if (enumm.variant === variant) {
return handler(enumm.value);
}
}
return handlers[symbolElse](unit);
}
export const makeConstructors = variantNames => {
if (new Set(variantNames).size !== variantNames.length) {
throw new Error("precondition failed: non-unique variant names");