js function currying realization

In the project, if you want to sum all the parameters of a function, you can take the following methods

function add () {
    
    
	let args = [...arguments]; // arguments一个类数组对象
	let sum = args.reduce((prev, next) => {
    
    
		return prev + next;
	});
	return sum;
}
add(1,2,3,4,5); // 15

If you want add(1)(2) to implement the sum operation like this, how should the function be written? After the function is executed, it must return a function, because () is a function that runs, so you will solve it like this:

function add(x) {
    
    
	return function (y) {
    
    
		return x + y;
	}
}
add(1)(2); // 3

But if the function has a lot of parameters or is uncertain, whether you want the function to be executed nested forever, this approach is not realistic, then we can solve this problem by another method, put all the parameters into an array In, the toString method is used to sum, which realizes the currying of the function.

 	function add() {
    
    
        var _args = [...arguments];
        var _adder = function() {
    
    
            _args.push(...arguments);
            return _adder;
        }
        _adder.toString = function() {
    
    
            return _args.reduce((prev, next) => {
    
    
                return prev + next;
            });
        }
        return _adder;
    }
    
    console.log(add(1, 2, 3, 4, 5)); // 15
    console.log(add(1)(2)); // 3
    console.log(add(1)(2, 3)); // 6

Guess you like

Origin blog.csdn.net/qq_42671194/article/details/108665900