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

How to implement function pipe using JavaScript, and throw errors?

  1. 我必须实现函数 pipe
  2. 该函数应该接受值和一系列函数。
  3. 每个函数都应该对提供的值进行操作,并将输出按顺序传递给另一个函数。
  4. 如果提供的参数不是函数,pipe 应立即抛出错误并停止执行。
  5. 使用函数isFunction,如果给出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 to use each function and pass the value as the accumulator, you can also use 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);