对比scala,用javascript实现curried方法

scala从语法上提供了curried方法,如:

def add(x: Int, y: Int, z: Int) = x + y + z
val addCurried = (add _).curried
add(1, 2, 3) // => 6
addCurried(1)(2)(3) // => 6

val add2 = (x: Int, y: Int, z: Int) => x + y + z
val addCurried2 = add.curried
add(1, 2, 3) // => 6
addCurried(1)(2)(3) // => 6

scala 在函数式和面向对象以及两者的结合上都比javascript走的更远,而且语法上相当的精简。
但是js也太灵活了,很多特性都和模拟出来。

用javascript 对 curried 方法的实现:
代码链接:https://github.com/peichao01/test2/tree/master/javascript/curried

Function.prototype.curried = function(argsLength){
     var self = this, len = argsLength === undefined ? self.length : argsLength;
     if(len > 0){
          function curried (time, stack){
               return function(x){
                    stack[time] = x;
                    if(stack.length < len) {
                         return curried(time + 1, stack.concat());
                    } else {
                         return self.apply(self, stack);
                    }
               }
          }
          return curried(0, []);
     }
     else{
          return function(){
               return self.apply(self);
          }
     }
};

var adder = function(x, y, z){ // 在 javascript 中使用函数定义,和将匿名函数赋值给变量基本上没有什么区别
    return x + y + z
}
var t = function(){}
var p = function (a) {
     return a + 1
}

// var a = adder.curried();
// var a1 = a(1)(2)(3);

var aa = adder.curried();
var aa1 = aa(1);
var aa2 = aa1(2);
var aa3 = aa2(3);
console.log(aa3);
console.log(aa1(-10)(23));

var ab2 = aa1(5);
var ab3 = ab2(6);
console.log(ab3);

console.log(aa(3)(5)(10));
console.log(aa(25)(50)(12));
console.log(aa1(-10)(23));

var t1 = t.curried();

var p1 = p.curried();
var p2 = p1(2);
    原文作者:超2真神
    原文地址: https://segmentfault.com/a/1190000000479493
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞