Pattern Matching in Typescript
Fast and efficient pattern matching in Typescript.
pattern<[number, number]>(1, 2)
.case(1, 2)(() => {})
.case("2", 3)(() => {}) // typescript throws compile error
.match();
pattern<[number, number]>(1, 2)
.case(2, 3)(() => {})
.match(); // pattern-case throws runtime error
Examples from the test cases
test('early exit if the condition has met', () => {
let executed = false;
pattern<[number, number, number]>(1, 2, 3)
.case(1, 2, 3)((a, b, c) => {return 1})
.case(1, 2, 3)((a, b, c) => {executed = true; return 1})
.match();
expect(executed).toBe(false);
});
The function next
could be used as a placeholder to continue with the next statement.
test('fall-through if the callback is not provided', () => {
const result = pattern<[number, number, number]>(1, 2, 3)
.case(1, 2, 3)(next)
.case(1, 2, 3)((a, b, c) => {return 1})
.match();
expect(result).toBe(1);
});
Happy hacking!