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);
}
}
答案 0 :(得分:3)
您可以编写一个包含这两个函数的函数,并将一个经过管理的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)
}
}
}
答案 1 :(得分:0)
另一种选择是在composeValidators
函数中使用composeAccreditionValidators
函数:
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}`;
}
}