@monstermann/match
Version:
Zero-runtime exhaustive pattern matching.
97 lines (94 loc) • 1.85 kB
JavaScript
//#region src/ExhaustiveMatch.ts
var ExhaustiveMatch = class {
constructor(value) {
this.value = value;
}
returnType() {
return this;
}
case() {
return this;
}
onCase() {
return this;
}
shape() {
return this;
}
onShape() {
return this;
}
cond() {
return this;
}
onCond() {
return this;
}
orThrow() {
return this.value;
}
or() {
return this.value;
}
orElse() {
return this.value;
}
};
//#endregion
//#region src/NonExhaustiveMatch.ts
var NonExhaustiveMatch = class {
constructor(value) {
this.value = value;
}
returnType() {
return this;
}
case(value, result) {
const v = this.value;
if (value !== v) return this;
return new ExhaustiveMatch(result);
}
onCase(value, fn) {
const v = this.value;
if (value !== v) return this;
return new ExhaustiveMatch(fn(value));
}
shape(value, result) {
const v = this.value;
if (!(value && typeof value === "object")) return this;
for (const key in value) if (value[key] !== v[key]) return this;
return new ExhaustiveMatch(result);
}
onShape(value, fn) {
const v = this.value;
if (!(value && typeof value === "object")) return this;
for (const key in value) if (value[key] !== v[key]) return this;
return new ExhaustiveMatch(fn(v));
}
cond(predicate, result) {
const v = this.value;
if (!predicate(v)) return this;
return new ExhaustiveMatch(result);
}
onCond(predicate, fn) {
const v = this.value;
if (!predicate(v)) return this;
return new ExhaustiveMatch(fn(v));
}
orThrow() {
throw new Error(`Pattern matching error: no pattern matches value ${JSON.stringify(this.value)}`);
}
or(fallback) {
return fallback;
}
orElse(fallback) {
return fallback(this.value);
}
};
//#endregion
//#region src/match.ts
function match(value) {
return new NonExhaustiveMatch(value);
}
//#endregion
export { match };