Skip to content

Instantly share code, notes, and snippets.

@framp
Last active April 25, 2016 10:07
Show Gist options
  • Save framp/8dafcacc83e9377104a65890fd705314 to your computer and use it in GitHub Desktop.
Save framp/8dafcacc83e9377104a65890fd705314 to your computer and use it in GitHub Desktop.
const equal = (a, b) => a === b
const create = (...args) => {
const rules = []
const creator = {
when(arg, valid, value, definition) {
const key = args.indexOf(arg)
rules[key] = rules[key] || []
rules[key].push([ (a) => valid(a, value), definition ])
return creator
},
done() {
return (...args) =>
args.reduce((fn, arg, key) =>
fn || rules[key] && rules[key].reduce((fn, [valid, definition]) =>
fn || valid(arg) && definition
, 0)
, 0)(...args)
}
}
return creator;
}
const math = create('a', 'b', 'c')
.when('a', equal, '*', (a, b, c) => b*c)
.when('a', equal, '+', (a, b, c) => b+c)
.when('a', equal, '-', (a, b, c) => b-c)
.when('a', equal, '/', (a, b, c) => b/c)
.done()
console.log('Matches first parameter, first rule:', math('*', 2, 3) === 6)
console.log('Matches first parameter, second rule:', math('+', 2, 3) === 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment