Skip to content

Instantly share code, notes, and snippets.

@ealush
Last active March 4, 2018 12:23
Show Gist options
  • Select an option

  • Save ealush/7a38c3693bac8a6cf55602ee017375fc to your computer and use it in GitHub Desktop.

Select an option

Save ealush/7a38c3693bac8a6cf55602ee017375fc to your computer and use it in GitHub Desktop.
enforce: it's christmas approach
// 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