UNPKG

@monstermann/match

Version:

Zero-runtime exhaustive pattern matching.

94 lines (90 loc) 1.79 kB
//#region src/Exhaustive.ts var Exhaustive = class { constructor(value) { this.value = value; } case() { return this; } cond() { return this; } onCase() { return this; } onCond() { return this; } or() { return this.value; } orElse() { return this.value; } orThrow() { return this.value; } returnType() { return this; } }; //#endregion //#region src/Value.ts var Value = class { constructor(value) { this.value = value; } case(value, result) { if (value !== this.value) return this; return new Exhaustive(result); } cond(predicate, result) { if (!predicate(this.value)) return this; return new Exhaustive(result); } onCase(value, result) { if (value !== this.value) return this; return new Exhaustive(result(value)); } onCond(predicate, result) { if (!predicate(this.value)) return this; return new Exhaustive(result(this.value)); } or(fallback) { return fallback; } orElse(fallback) { return fallback(this.value); } orThrow() { throw new Error(`Pattern matching error: no pattern matches value ${this.value}`); } returnType() { return this; } }; //#endregion //#region src/Shape.ts var Shape = class extends Value { case(value, result) { for (const key in value) if (this.value[key] !== value[key]) return this; return new Exhaustive(result); } onCase(value, result) { for (const key in value) if (this.value[key] !== value[key]) return this; return new Exhaustive(result(this.value)); } orThrow() { throw new Error(`Pattern matching error: no pattern matches value ${JSON.stringify(this.value)}`); } }; //#endregion //#region src/match.ts const match = function(value) { return new Value(value); }; match.shape = function(value) { return new Shape(value); }; //#endregion export { match };