How can I make var a = add(2)(3); //5 work?

后端 未结 28 2350
长发绾君心
长发绾君心 2020-11-27 14:11

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\

28条回答
  •  粉色の甜心
    2020-11-27 14:39

    This is a generalized solution which will solve add(2,3)(), add(2)(3)() or any combination like add(2,1,3)(1)(1)(2,3)(4)(4,1,1)(). Please note that few security checks are not done and it can be optimized further.

    function add() {
    	var total = 0;
    
    	function sum(){
    		if( arguments.length ){
    			var arr = Array.prototype.slice.call(arguments).sort();
    			total = total + arrayAdder(arr);
    			return sum;
    		}
    		else{
    			return total;
    		}
    	}
    
    	if(arguments.length) {
    		var arr1 = Array.prototype.slice.call(arguments).sort();
    		var mytotal = arrayAdder(arr1);
    		return sum(mytotal);
    	}else{
    		return sum();
    	}
    
    	function arrayAdder(arr){
    		var x = 0;
    		for (var i = 0; i < arr.length; i++) {
    			x = x + arr[i];
    		};
    		return x;
    	}
    }
    add(2,3)(1)(1)(1,2,3)();

提交回复
热议问题