代码之家  ›  专栏  ›  技术社区  ›  totalnoob

咖喱-如何获得args的计数?

  •  0
  • totalnoob  · 技术社区  · 8 年前

    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 回复  |  直到 8 年前
        1
  •  2
  •   Jonas Wilms    8 年前

    你不能。诀窍在于,例如记录一个值,例如:

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

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

    所以你只需要设定一个习惯 toString 返回函数的方法,例如:

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