Last active
March 4, 2018 12:23
-
-
Save ealush/7a38c3693bac8a6cf55602ee017375fc to your computer and use it in GitHub Desktop.
enforce: it's christmas approach
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
| // import rules from './rules.js'; | |
| // This is a `rule runner` It runs the rule it gets | |
| // * throws an error on failure | |
| // * returns the wrapped rules object on success so you can keep on chaining | |
| function ruleRunner(rule, wrapped, value, ...args) { | |
| const result = rule(value, ...args); | |
| // if the result is not explicitly true, throw | |
| if (result !== true) { | |
| throw new Error(`validation failed for ${rule.name}`); | |
| } | |
| // return the wrapped rules object | |
| return wrapped; | |
| } | |
| // Start here! | |
| function enforce(value) { | |
| const wrapped = {}; | |
| // iterate over all functions | |
| Object.keys(rules).forEach((fnName) => { | |
| // wrap each function with ruleRunner | |
| // and pass down the initial value and args | |
| wrapped[fnName] = (...args) => ruleRunner(rules[fnName], wrapped, value, ...args); | |
| }); | |
| return wrapped; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment