What is 'Currying'?

前端 未结 18 1250
遥遥无期
遥遥无期 2020-11-21 05:26

I\'ve seen references to curried functions in several articles and blogs but I can\'t find a good explanation (or at least one that makes sense!)

18条回答
  •  死守一世寂寞
    2020-11-21 06:11

    Currying is one of the higher-order functions of Java Script.

    Currying is a function of many arguments which is rewritten such that it takes the first argument and return a function which in turns uses the remaining arguments and returns the value.

    Confused?

    Let see an example,

    function add(a,b)
        {
            return a+b;
        }
    add(5,6);
    

    This is similar to the following currying function,

    function add(a)
        {
            return function(b){
                return a+b;
            }
        }
    var curryAdd = add(5);
    curryAdd(6);
    

    So what does this code means?

    Now read the definition again,

    Currying is a function of many arguments which is rewritten such that it takes first argument and return a function which in turns uses the remaining arguments and returns the value.

    Still, Confused? Let me explain in deep!

    When you call this function,

    var curryAdd = add(5);
    

    It will return you a function like this,

    curryAdd=function(y){return 5+y;}
    

    So, this is called higher-order functions. Meaning, Invoking one function in turns returns another function is an exact definition for higher-order function. This is the greatest advantage for the legend, Java Script. So come back to the currying,

    This line will pass the second argument to the curryAdd function.

    curryAdd(6);
    

    which in turns results,

    curryAdd=function(6){return 5+6;}
    // Which results in 11
    

    Hope you understand the usage of currying here. So, Coming to the advantages,

    Why Currying?

    It makes use of code reusability. Less code, Less Error. You may ask how it is less code?

    I can prove it with ECMA script 6 new feature arrow functions.

    Yes! ECMA 6, provide us with the wonderful feature called arrow functions,

    function add(a)
        {
            return function(b){
                return a+b;
            }
        }
    

    With the help of the arrow function, we can write the above function as follows,

    x=>y=>x+y
    

    Cool right?

    So, Less Code and Fewer bugs!!

    With the help of these higher-order function one can easily develop a bug-free code.

    I challenge you!

    Hope, you understood what is currying. Please feel free to comment over here if you need any clarifications.

    Thanks, Have a nice day!

提交回复
热议问题