export const composeValidators = (...validators) => value => validators.reduce((error, validator) => error || validator(value), undefined);
export const composeAccreditionValidators = (... validators) => value => validators.reduce((error, validator) => validator(value) === undefined ? error : `! ${validator(value)}`, undefined);
I am trying to create the second function exclusively for just one of my components and would prefer having the second one call the first one. Syntactically I may be making a few mistakes, and hence the code is blowing up on me. Can someone assist?
NOTE: I would like to keep the logic of the second one intact. Essentially it wraps the output string in a ! and a space unlike the first one.
Edit: Here are the same functions written, so they are easier to read.
function composeValidators(...validators) {
return function (value) {
return validators.reduce((error, validator) => (
error || validator(value)
), undefined)
}
}
function composeAccreditionValidators(...validators) {
return function (value) {
return validators.reduce((error, validator) => (
validator(value) === undefined
? error
: `! ${validator(value)}`
), undefined);
}
}
You could write a function that composes both of these functions, and takes a curried reducer
function as input:
const createComposeValidators = reducer => (...validators) => value =>
validators.reduce(reducer(value), undefined)
export const composeValidators = createComposeValidators(
value => (error, validator) =>
error || validator(value)
)
export const composeAccreditionValidators = createComposeValidators(
value => (error, validator) =>
validator(value) === undefined ? error : `! ${validator(value)}`
)
Here is the same function written so it is easier to read:
function createComposeValidators(reducer) {
return function composeValidators(...validators) {
return function (value) {
return validators.reduce(reducer(value), undefined)
}
}
}