Skip to content

Instantly share code, notes, and snippets.

@hew
Forked from phpnode/match.js
Last active June 9, 2019 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hew/12371edbc1df776ff77537517cee786d to your computer and use it in GitHub Desktop.
Save hew/12371edbc1df776ff77537517cee786d to your computer and use it in GitHub Desktop.

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