Home  >  Q&A  >  body text

currying - Javascript 连续调用单参函数实现任意参函数

函数 add 可以实现连续的加法运算
函数 add 语法如下 add(num1)(num2)(num3)...; //注意这里是省略号哟,可无限

使用举例如下:

add(10)(10); // 20
add(10)(20)(50); // 80
add(10)(20)(50)(100); // 180

var add30 = add(10)(20); // 30
var add100 = add30(30)(40); // 100
var add31 = add30(1); // 31
var add40 = add31(9); // 40
天蓬老师天蓬老师2655 days ago1367

reply all(14)I'll reply

  • 大家讲道理

    大家讲道理2017-04-10 15:30:14

    网易的考试题...哈哈~

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-10 15:30:14

    顶上去啊 自己还没想出来!

    reply
    0
  • 阿神

    阿神2017-04-10 15:30:14

    好像是通过拓展Number.prototype可以解决吧。

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-10 15:30:14

    那样写扩展性也不好吧。

    下面是我的思路。

    function Result() {
        this.result = 0;
    }
    
    //加法
    Result.prototype.add = function(value) {
        this.result = isNaN(value) ? this.result : this.result + value;
        return this;
    }
    
    //减法
    Result.prototype.sub = function(value) {
        this.result = isNaN(value) ? this.result : this.result - value;
        return this;
    }
    
    Result.prototype.getResult = function() {
        return this.result;
    }
    

    类似于这种的思路。

    调用

    var result = new Result();
    result.add(1).add(2).sub(3);
    retult.getResult();
    

    reply
    0
  • Cancelreply