What is 'Currying'?

前端 未结 18 1256
遥遥无期
遥遥无期 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:12

    Curry can simplify your code. This is one of the main reasons to use this. Currying is a process of converting a function that accepts n arguments into n functions that accept only one argument.

    The principle is to pass the arguments of the passed function, using the closure (closure) property, to store them in another function and treat it as a return value, and these functions form a chain, and the final arguments are passed in to complete the operation.

    The benefit of this is that it can simplify the processing of parameters by dealing with one parameter at a time, which can also improve the flexibility and readability of the program. This also makes the program more manageable. Also dividing the code into smaller pieces would make it reuse-friendly.

    For example:

    function curryMinus(x) 
    {
      return function(y) 
      {
        return x - y;
      }
    }
    
    var minus5 = curryMinus(1);
    minus5(3);
    minus5(5);
    

    I can also do...

    var minus7 = curryMinus(7);
    minus7(3);
    minus7(5);
    

    This is very great for making complex code neat and handling of unsynchronized methods etc.

提交回复
热议问题