Last active
April 25, 2016 10:07
-
-
Save framp/8dafcacc83e9377104a65890fd705314 to your computer and use it in GitHub Desktop.
This file contains 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 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