Skip to content

Instantly share code, notes, and snippets.

@louiezhao
Created March 27, 2018 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louiezhao/1e7de5f3cb6254be5f6e4db632ad902f to your computer and use it in GitHub Desktop.
Save louiezhao/1e7de5f3cb6254be5f6e4db632ad902f to your computer and use it in GitHub Desktop.
const _ = require('lodash');
const aMap = (obj) => _.isObject(obj);
const validator = (msg, aChecker) => {
const f = function () {
return aChecker.apply(aChecker, arguments);
};
f['msg'] = msg;
return f;
// aChecker.msg = msg;
// return aChecker;
}
function hasKeys() {
const keys = _.toArray(arguments);
const f = (obj) => _.every(keys, key => _.has(obj, key));
f.msg = _.concat('must have keys:', keys).join(' ');
return f;
}
function validateWithRules() {
const validators = _.toArray(arguments);
return (obj) => {
const errors = _.reduce(validators, (errors, validator) => {
if (validator(obj)) {
return errors;
} else {
return _.chain(errors).push(validator.msg).value();
}
}, []);
console.log(errors);
return errors;
};
};
const validate = validateWithRules(
validator('must be a map', aMap),
hasKeys('msg', 'type')
);
validate({ msg: 'blah', type: 'display' });
validate(32);
validate({});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment