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);
我正在尝试专门为我的一个组件创建第二个函数,并且希望让第二个函数调用第一个函数。从语法上讲,我可能会犯一些错误,因此代码在我身上爆炸了。有人可以协助吗?
注意:我想保持第二个逻辑不变。本质上,它将输出字符串包装在 !以及一个与第一个不同的空间。
编辑:这是编写的相同函数,因此它们更易于阅读。
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);
}
}
您可以编写一个函数来组合这两个函数,并将柯里reducer
函数作为输入:
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)}`
)
这是编写的相同函数,因此更易于阅读:
function createComposeValidators(reducer) {
return function composeValidators(...validators) {
return function (value) {
return validators.reduce(reducer(value), undefined)
}
}
}
另一种选择是在composeAccreditionValidators
函数中使用composeValidators
函数:
function composeValidators(...validators) {
return function (value) {
return validators.reduce((error, validator) => (
error || validator(value)
), undefined)
}
}
function composeAccreditionValidators(...validators) {
const validate = composeValidators(...validators);
return function (value) {
const error = validate(value);
return error && `! ${error}`;
}
}