It is interesting to see a question: how to deal with the following function, which is aggregated into a function and passes the return value of the first function to the next function.

function f1(arg) {
  console.log("f1", arg);
  return arg;
}
function f2(arg) {
  console.log("f2", arg);
  return arg;
}
function f3(arg) {
  console.log("f3", arg);
  return arg;
}
Copy the code

Of course, the simplest implementation is function execution, as a function as arguments nested execution

let res = f1(f2(f3(“omg”))); If you want to use a function to do this, you need reduce to do it

let res = compose(f1, f2, f3)("omg");
functioncompose(... Funcs) {// Use reduce processingreturnfuncs.reduce((a, b) => (... args) => a(b(... args))); }Copy the code

Let’s think about the case where there’s no value passed, and we need to make one more judgment

let res = compose()("omg");
functioncompose(... funcs) {if (funcs.length === 0) {
    // returnarg => arg; / / orreturn() = > {}; }if (funcs.length === 1) {
    return funcs[0];
  }
  returnfuncs.reduce((a, b) => (... args) => a(b(... args))); }Copy the code