Skip to content

Instantly share code, notes, and snippets.

@hew
Forked from phpnode/match.js
Last active Jun 9, 2019
Embed
What would you like to do?

reasonml pattern matching in javascript...as best it can be

const invalidMatchSignal = new Error();
function makeProxyThrower(input) {
return new Proxy(input, {
get(target, prop, receiver) {
if (prop in target) {
const result = Reflect.get(target, prop, receiver);
if (typeof result === 'object' && result !== null) {
return makeProxyThrower(result);
}
return result;
}
throw invalidMatchSignal;
}
});
}
export function match(input = {}, ...patterns) {
const safeInput = Object.keys(input).length ? input : { error: '' };
const param = makeProxyThrower(safeInput);
for (const pattern of patterns) {
try {
return pattern(param);
} catch (e) {
if (e !== invalidMatchSignal) {
throw e;
}
}
}
throw new Error('No match for input');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment