currying - how to get the count of args?

时间:2018-09-18 19:33:29

标签: javascript

in a sum function that returns the sum of (1)(2)(3), (1,2)(2) as well as (1,2), how do I write logic to determine if there were just one argument (1,2) or there were more than one (1,2)(2) or (1)(2)(3) in order to return the value properly

function sum (...x) {
  let total = 0;

  if (x.length > 1) {
    total += x.reduce((a, b) => a + b);
  } else {
    total += x;
  }
  // return total if no other arguments;
  
  return (y) => {
    total += y;
    // return total if no other arguments;

    return (z) => {
      total += z;
      // return total if no other arguments;
    }
  }
}

sum(1,2);
sum(1,2)(3);

1 个答案:

答案 0 :(得分:2)

You can't. The trick is that for example logging a value such as:

 console.log(
  sum(1),
  sum(1)(2) 
 );

tries to turn the function into a string, so it is actually the same as:

 console.log( 
   sum(1).toString(),
   sum(1)(2).toString()
);

So you just have to set a custom toString method to the returned function, e.g.:

 function sum(...values) {
  let result = values.reduce((a, b) => a + b, 0);
  function curry(...values) {
    return sum(result, ...values);
  }
  curry.toString = () => "" + result; // <<
  return curry;
 }