Function currying (curry)

We still start from the demand. Only by knowing what we are going to do can we guide us step by step to build tall buildings.
First look at the following code:

  		function add(x,y){
    
    
            return x+y
        }
        console.log(add(3,1))//4

If we want to execute add(3)(1) in this way and also output 4, what should we do. We can know from this function call that the function is called twice, and the function returned after the first call can be called again. The first call passes in parameters, the second call also passes in parameters, and the two passed-in parameters are added up. So we have:

		 function add(x){
    
    
            return function(y){
    
    
                return x+y
            }
        }
        console.log(add(3)(1))//4

Extending to our other requirement, we assume let testNumber=regNumber(/\d+/), and then testNumber('123abd'), testNumber('abc') to judge whether the passed parameter satisfies the regularity. Obviously it can be realized. The advantage of such a function is that we only need to write the regular judgment once, and there is no need to write it later, which is very convenient. According to this requirement, we can write:

		function regNumber(reg,str){
    
    
           return function (str){
    
    
                return reg.test(str)
           }
        }
        let testNumber=regNumber(/\d+/g)
        console.log(testNumber('123abc'))//true
        console.log(testNumber('abc'))//false

Going back to the previous add function, if we want to call it as many times as we want, for example add(1)(2)(3)(4)...to achieve 1+2+3+...add to the desired effect What should we do? This is obviously returning a function after calling a function, so we can define a function to return to itself, and finally use the feature of toString implicit conversion, when the final execution is implicit conversion, and calculate the final value Return, the code is as follows:

function add() {
    
    
            let args = [...arguments]
            let _adder = function () {
    
    
                args.push(...arguments)
                return _adder
            }
            _adder.toString = function () {
    
    //利用隐式转换最后执行
                return args.reduce(function (a, b) {
    
    
                    return a + b;
                });
            }
            return _adder
        }
        console.log(add(1)(2)(3))//6

So far we seem to have not said what currying is. From the above we can see that when currying is called, other functions can be different. It is called one by one, describing f(x)(y )(z)...This kind. So in the future, the comparison of calling a function like this is to use currying, and the function inside the cocoa will always return to the function, and the last return is the desired result.

Guess you like

Origin blog.csdn.net/weixin_44494811/article/details/113791898