Wednesday, July 5, 2017

add - Currying

Question: How would you make this work?
add(2, 5); // 7
add(2)(5); // 7
@reference_1_github.com

A:
function add_(a){   
    return function(b){
        return a + b;
    };
}
function add(a){
   var acc = 0;
   var sub = function(b){
       if(b === undefined)
         return acc;
       else if(!isNaN(b))
         acc += b;
       return sub;
   };
   return sub(a);
}

@reference_2_codeburst.io

No comments:

Post a Comment