On the Corialization of functions

implementation of function Corialization seen on the Internet js Advanced tutorial

about implementing an add method, the calculation results can satisfy the following expectations:: add (1) (2) (3) = 6 add (1, 2, 3) (4) = 10 add (1) (2) (3) (4) (5) = 15

function add() {
    // 
    var _args = [].slice.call(arguments);

    // _args
    var adder = function () {
        var _adder = function() {
            [].push.apply(_args, [].slice.call(arguments));
            return _adder;
        };

        // 
        _adder.toString = function () {
            return _args.reduce(function (a, b) {
                return a + b;
            });
        }

        return _adder;
    }
    return adder.apply(null, [].slice.call(arguments));
}

// 
console.log(add(1, 2, 3, 4, 5));  // 15
console.log(add(1, 2, 3, 4)(5));  // 15
console.log(add(1)(2)(3)(4)(5));  // 15

I don"t understand the function _ adder that collects parameters, so why does it return itself, and it"s not a recursive call? After I remove this sentence, I will report an error
add (.) (.). Is not a function

Nov.20,2021

Why does it return itself
To put it simply, is to make the parameters of a function execute

after passing in parameters many times.

the implementation of "passing parameters multiple times" requires that after each passing parameter execution, except for the last execution, the return value of the calling function must be a function

.
after I remove this sentence, I will report an error
add (.) (.) Is not a function

the default return undefined is removed.

< hr >

take a chestnut:

function add() {
    // 
    var _args = [].slice.call(arguments);

    // _args
    var adder = function () {
        var _adder = function() {
            [].push.apply(_args, [].slice.call(arguments));
            return _adder;
        };

        // 
        _adder.toString = function () {
            return _args.reduce(function (a, b) {
                return a + b;
            });
        }

        return _adder;
    }
    return adder.apply(null, [].slice.call(arguments)); }

//  console.log(add(1, 2, 3, 4, 5));  // 15
console.log(add(1, 2, 3, 4)(5));  // 15
console.log(add(1)(2)(3)(4)(5));  // 15
The main purpose of the implementation of

above, taking advantage of the features of closures, is to collect all the parameters in an array through some clever methods, and to add up all the items in the array during the final implicit conversion. So when we call the add method, the parameters are very flexible. Of course, it is very easy to meet our needs.

Menu