• Currying is the technique of taking a function that takes multiple arguments and turning it into a function that takes a single argument (the first argument of the original function), and returning a new function that takes the rest of the arguments and returns a result.

  • Popular explanation:

    • Currying is when a function that has multiple arguments is passed one, and a new function is generated that takes the remaining arguments and runs it to get the result.
    • Two interesting concepts similar to Currie ====> Partial functions and higher order functions Do you know his definition? The answer will be given briefly below.
  • In JavaScript Advanced programming it is described as follows:

    • Curlized functions are usually created dynamically by calling another function and passing it the function to be curlized and the necessary arguments.
    • General way:
    function curry(fn){
        var args = Array.prototype.slice.call(arguments.1);
        return function(){
            var innerArgs = Array.prototype.slice.call(arguments);
            var finalArgs = args.contact(innerArgs);
            return fn.apply(null,finalArgs); }}function add (num1,num2){
        return num1 + num2;
    }
    var curriedAdd = curry(add,5);
    alert(curriedAdd(3);/ / 8
    Copy the code
    • There is also an example in the book of the combination of Currying and binding functions:
      function bind(fn,context){
          var var args = Array.prototype.slice.call(arguments.2);
          return function(){
              var innerArgs = Array.prototype.slice.call(arguments);
              var finalArgs = args.contact(innerArgs);
              returnfn.apply(context,finalArgs); }}// Powerful dynamic function creation can be achieved by currying and binding functions.
      Copy the code

    Above is the explanation and simple example of currying in JavaScript advanced programming.

  • Now I’m going to ask you how to tell if a tag is a native HTML tag, and I’ll give you two minutes to think about it.

    • Simple implementation: Very simple
        var str = 'html,body,base,head,link,meta,style,title,' +
            'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
            'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' +
            'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
            's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
            'embed,object,param,source,canvas,script,noscript,del,ins,' +
            'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
            'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
            'output,progress,select,textarea,' +
            'details,dialog,menu,menuitem,summary,' +
            'content,element,shadow,template,blockquote,iframe,tfoot';
        function isHTMLTag ( tag, str ) {
            var list = str.split(', ');
            var flag =false;
            for (var i = 0; i < list.length; i++) {
                if(list[i] == tag){
                    flag = true;
                    break; }}return flag;
        }
        var isHTMLTag = isHTMLTag('div',str);
      Copy the code
    • This method is super easy to implement, but this method alone is fine, but if we call it 100 times, we’re going to loop (100 times the number of STR).
    • You might say that without a for loop, there is no loop with indexOf, but the inner implementation of indexOf also has a loop.
  • Let’s look at how this functionality is implemented in the source code of the familiar Vue framework.

    • Source code is through function currie, closures and other techniques to optimize our operations.
        /** * Make a map and return a function for checking if a key * is in that map. */
        function makeMap ( str, expectsLowerCase ) {
            var map = Object.create(null);
            var list = str.split(', ');
            for (var i = 0; i < list.length; i++) {
                map[list[i]] = true;
            }
            return expectsLowerCase
                ? function (val) { return map[val.toLowerCase()]; }
                : function (val) { returnmap[val]; }}var isHTMLTag = makeMap(
            'html,body,base,head,link,meta,style,title,' +
            'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
            'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' +
            'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
            's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
            'embed,object,param,source,canvas,script,noscript,del,ins,' +
            'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
            'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
            'output,progress,select,textarea,' +
            'details,dialog,menu,menuitem,summary,' +
            'content,element,shadow,template,blockquote,iframe,tfoot'
        );
        var isTextInputType = makeMap('text,number,password,search,email,tel,url');// This is to determine whether the input box is valid
        var isHTMLTag = isHTMLTag('div');
        // In Vue's source code, all native Html tags are enumerated
    Copy the code
    • Initialization but source is only called when the number of (STR), then each time you use because the function is changed because of the closure curry only need according to the value of the map to retrieve, performance is a lot of ascension, although the code quantity is much, also lost a part of the performance and increase the additional overhead, but a lot of improved its overall performance.
    • This makeMap method can be used in our own projects, can also be a bright spot yo.
  • Ok, that’s about the basics, now let’s look at some interview questions about currie.

    1. Add (1) (2) (3) (4)… It’s infinite.
    2. Add (1) (2) (3) (4)… And support add(1,2)(3,4)(5).. Or add (1, 2, 3, 4, 5).
      • Let’s solve the infinite accumulation problem first

      • To solve this problem, the toString method is used to return the current object as a String. The toString() function returns a String value that returns the current object as a String, and many Built-in objects in JavaScript override this function to better suit their functional needs.

            function add(a){
                function s(b){
                    a = a + b;
                    return s;
                }
                s.toString = function(){
                    return a;
                }
                return s;
            }
            var a = add(1) (2) (3) (4).toString();/ / 10
        Copy the code
      • Now let’s solve the second problem. What do we do with the next one

            var a = add(1) (2) (3) (4);   / / 10
            var b = add(1.2.3.4);   / / 10
            var c = add(1.2) (3.4);   / / 10
            var d = add(1.2.3) (4);   / / 10
            
            function add() {
                var args = Array.prototype.slice.call(arguments);// Turn pseudo-array into array
                function hardAdd() {
                    var innerArgs = Array.prototype.slice.call(arguments.0);// Turn pseudo-array into array
                    args = args.concat(innerArgs);// Merge parameters
                    return hardAdd;
                }
                hardAdd.toString = function () {// Override the toString method
                    return args.reduce((previous, current) = > {// Use reduce to add
                        return previous + current
                    });
                }
                return hardAdd;
            }
        Copy the code
    3. There’s actually one more problemNumber of known parameters, the number of parameters accumulated after the return result, you can try
          fn(a,b,c,d) => fn(a)(b)(c)(d);/ / this
          // Note :fn. Length returns what? Hope to leave a message
      Copy the code
  • Oh, right, next with you to say the definition of partial functions and higher order functions (also put together, easy for you to compare). (ps: I think it can only pass a parameter at a time to be currie, but not completely)

    • Curryization: a function that has multiple arguments, passes only one argument, generates a new function, which takes the remaining arguments and runs the result.
    • Partial function: a function that has multiple arguments, passes only some of the arguments, generates a new function, which takes the remaining arguments and runs the result.
    • Higher-order function: A function argument is a function that is processed to produce a function, which is either a higher-order function or a function as a return value.