Skip to content

Instantly share code, notes, and snippets.

@tstelzer
Last active January 27, 2018 15:45
Show Gist options
  • Save tstelzer/2a80fecc1f198b9b414a969798a8d264 to your computer and use it in GitHub Desktop.
Save tstelzer/2a80fecc1f198b9b414a969798a8d264 to your computer and use it in GitHub Desktop.
simple-functional-validation.js
const isEven = n => (n % 2 === 0)
const gte = min => n => n >= min
const isNil = x => x === undefined || x === null
const validatorA = {
pred: isEven,
message: n => `"${n}" should be an even number.`,
accessor: obj => obj.num1,
}
const validatorB = {
pred: gte(20),
message: n => `"${n}" should be greater than or equal to 20`,
accessor: obj => obj.num2,
}
console.log(makeValidate([validatorA, validatorB])({value: {name: 'Jeff', num1: 43, num2: 15}}))
// {
// value: { name: 'Jeff', num1: 43, num2: 15 },
// messages: [
// '"43" should be an even number.',
// '"15" should be greater than or equal to 20',
// ]
// }
const validatorC = {
pred: a => !isNil(a),
message: _ => 'Please provide a value.',
}
console.log(makeValidate([validatorC])({value: undefined}))
// { value: undefined, messages: [ 'Please provide a value.' ] }
const makeValidate = validators =>
({value, messages = []}) =>
validators.reduce((result, validator) => {
const {pred, accessor = x => x, message} = validator
return pred(accessor(value))
? result
: {value, messages: result.messages.concat(message(accessor(value)))}
}, {value, messages})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment