reasonml pattern matching in javascript...as best it can be
-
-
Save hew/12371edbc1df776ff77537517cee786d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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