Skip to content

Instantly share code, notes, and snippets.

@lincore81
Last active March 22, 2018 13:43
Show Gist options
  • Select an option

  • Save lincore81/ab6c1e6c43962a798191fc764923b4b2 to your computer and use it in GitHub Desktop.

Select an option

Save lincore81/ab6c1e6c43962a798191fc764923b4b2 to your computer and use it in GitHub Desktop.
const otherwise = true;
const isNumber = n => typeof n === 'number';
const eq = a => b => a === b;
const fib = match([
eq(0), 1,
eq(1), 1,
x < 0, 0,
isNumber, () => fib(x-1) + fib(x-2),
otherwise, () => {throw new Error('Not a number');}
]);
function match(conds) {
return (x) => {
if (conds.length % 2) throw new Error('array must have an even length.');
for (let i = 0; i < conds.length; i+=2) {
const cond = conds[i];
let pass = eval(cond, x);
if (!pass) continue;
return eval(conds[i+1], pass);
}
throw new Error(`Unmatched value: ${x}`);
}
function eval(expr, arg) {
if (typeof expr === 'function') {
return expr(arg)
}
return expr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment