I want to make this syntax possible:
var a = add(2)(3); //5
based on what I read at http://dmitry.baranovskiy.com/post/31797647
I\
Concept of CLOSURES can be used in this case.
The function "add" returns another function. The function being returned can access the variable in the parent scope (in this case variable a).
function add(a){
return function(b){
console.log(a + b);
}
}
add(2)(3);
Here is a link to understand closures http://www.w3schools.com/js/js_function_closures.asp
function A(a){
return function B(b){
return a+b;
}
}
I found a nice explanation for this type of method. It is known as Syntax of Closures
please refer this link Syntax of Closures
function add () {
var args = Array.prototype.slice.call(arguments);
var fn = function () {
var arg_fn = Array.prototype.slice.call(arguments);
return add.apply(null, args.concat(arg_fn));
}
fn.valueOf = function () {
return args.reduce(function(a, b) {
return a + b;
})
}
return fn;
}
console.log(add(1));
console.log(add(1)(2));
console.log(add(1)(2)(5));
from http://www.cnblogs.com/coco1s/p/6509141.html
try this will help you in two ways add(2)(3) and add(2,3)
1.)
function add(a){ return function (b){return a+b;} }
add(2)(3) // 5
2.)
function add(a,b){
var ffffd = function (b){return a+b;};
if(typeof b =='undefined'){
return ffffd;
}else{
return ffffd(b);
}
}
add(2)(3) // 5
add(2,3) // 5
let multi = (a)=>{
return (b)=>{
return (c)=>{
return a*b*c
}
}
}
multi (2)(3)(4) //24
let multi = (a)=> (b)=> (c)=> a*b*c;
multi (2)(3)(4) //24
It's about JS curring and a little strict with valueOf
:
function add(n){
var addNext = function(x) {
return add(n + x);
};
addNext.valueOf = function() {
return n;
};
return addNext;
}
console.log(add(1)(2)(3)==6);//true
console.log(add(1)(2)(3)(4)==10);//true
It works like a charm with an unlimited adding chain!!