Pipe function и try ... catch errors
Пытаюсь написать pipe function, которая, в случае отризательной проверки isFunction будет возвращать сообщение об ошибке, и которая, в случае isFunction = true, будет производить расчет.
На данный момент в рамках текущего кода оба раза функция возвращает сообщение об ошибке: Provided argument at position 2 is not a function! - как и должно быть prevFn is not a function - быть не должно, т.к. при втором вызове функции const result передуется 3 функции.
Подскажите, пожалуйста, как возможно устранить ошибку?
function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
const pipe = (value, ...funcs) => {
try {
let _pipe = (prevFn, nextFn) => (value) = nextFn(prevFn(value));
let result = funcs.reduce((prevFn, nextFn) => {
if(!isFunction(nextFn)) {
throw new SyntaxError('Provided argument at position 2 is not a function!');
} else {
return _pipe(prevFn, nextFn);
}
});
return result;
} catch (error) {
return error.message;
}
};
const replaceUnderscoreWithSpace = (value) => value.replace(/_/g, ' ');
const capitalize = (value) =>
value
.split(' ')
.map((val) => val.charAt(0).toUpperCase() + val.slice(1))
.join(' ');
const appendGreeting = (value) => `Hello, ${value}!`;
const error = pipe('john_doe', replaceUnderscoreWithSpace, capitalize, '');
alert(error); // Provided argument at position 2 is not a function!
const result = pipe('john_doe', replaceUnderscoreWithSpace, capitalize, appendGreeting);
alert(result); // Hello, John Doe!
Ответы (1 шт):
Автор решения: vsemozhebuty
→ Ссылка
Если я правильно понимаю ваш код, то могу предположить две ошибки:
- Опечатка
=вместо=>. Вместо:
let _pipe = (prevFn, nextFn) => (value) = nextFn(prevFn(value));
нужно:
let _pipe = (prevFn, nextFn) => (value) => nextFn(prevFn(value));
- Поскольку редьюсером возвращается функция, нужно вызвать её в самом конце последний раз. Вместо:
return result;
нужно:
return result(value);
function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
const pipe = (value, ...funcs) => {
try {
let _pipe = (prevFn, nextFn) => (value) => nextFn(prevFn(value));
let result = funcs.reduce((prevFn, nextFn) => {
if(!isFunction(nextFn)) {
throw new SyntaxError('Provided argument at position 2 is not a function!');
} else {
return _pipe(prevFn, nextFn);
}
});
return result(value);
} catch (error) {
return error.message;
}
};
const replaceUnderscoreWithSpace = (value) => value.replace(/_/g, ' ');
const capitalize = (value) =>
value
.split(' ')
.map((val) => val.charAt(0).toUpperCase() + val.slice(1))
.join(' ');
const appendGreeting = (value) => `Hello, ${value}!`;
const error = pipe('john_doe', replaceUnderscoreWithSpace, capitalize, '');
alert(error); // Provided argument at position 2 is not a function!
const result = pipe('john_doe', replaceUnderscoreWithSpace, capitalize, appendGreeting);
alert(result); // Hello, John Doe!