如何使用JavaScript实现函数管道,并抛出错误?


  1. 我必须实现函数管道
  2. 函数应该接受值和一系列函数。
  3. 每个函数都应该对提供的值进行操作,并将输出按顺序传递给另一个函数。
  4. 如果提供的参数不是一个函数,pipe应该立即抛出错误并停止执行。
  5. 使用函数isFunction
  6. 返回false,抛出错误。

这是我到目前为止的内容:

function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
////////////////// Implementing pipe function ////////////////////
const pipe = (value, ...funcs) => {
try {
const result = funcs.reduce(function (acc, currFunc) {
if (isFunction(currFunc) === false)
throw new ('Provided argument at position 2 is not a function!');
return currFunc(acc);
}, value);
return result;
} catch (err) {
return err.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!
我找不到解决办法。也许有人能帮我。提前谢谢。

您可以使用Array#reduce来使用每个函数并将值作为累加器传递,您也可以使用instanceofFunction来确保每个参数都是函数。

const isFunction = (func) => func instanceof Function;
const pipe = (value, ...funcs) => {
return funcs.reduce((acc, func, idx) => {
if (!isFunction(func)) {
throw new Error(
`Provided argument at position ${idx} is not a function!`
);
}
return func(acc);
}, value);
};
const split = (x) => x.split("");
const reverse = (x) => x.reverse();
const join = (x) => x.join("");
const test = pipe("a man a plan a canal, panama", split, reverse, join);
console.log(test);

相关内容

最新更新