Functional Programming of JS

1. Application of Function Combination

A new function is composed of several pure functions, partial functions and Curitization functions. At the same time, data transfer is formed.
A series of functions are selected and combined to achieve the effect of public cooperation.

Code example:

function combination() {
        var args = Array.prototype.slice.call(arguments);
        return function(x) {
        
   			// ReducRight's specific approach allows you to view official documents
          return args.reduceRight(function(res, ele) { 
            return ele(res);
          }, x);
        };
      }
      var arr = combination(add, spl, toUpper) // Three functions. The data of three functions are all related.
      		console.log(arr("tzh")); // The print result is TZH520!!!
 	  function toUpper(str) {
        return str.toUpperCase();
      }
      
      function add(str) {
        return str + "!!!";
      }

      function spl(str) {
        return str + "520";
      }

Functions combine to transfer data from left to right.

2. curry

In mathematics and computer science, coritization is a technique for converting a function using multiple parameters into a series of functions using one parameter.

  • Why use curry

Simplify code structure, improve system maintainability, a method, a parameter, function cohesion, reduce coupling

Code simulation coritization

	function add(a, b, c, d) {
        return a + b + c + d;
      }
      
      //Intercept arguments arguments and return a function
      function agent(fn) {
        var args = Array.prototype.slice.call(arguments, 1);
        return function() {
          var arr = args.concat(Array.prototype.slice.call(arguments, 0));

          return fn.apply(this, arr);
        };
      }
	// Core Idea Code of Curitization
	function currie(fn, length) {
        var length = length || fn.length;

        return function() {
          var arg_len = arguments.length;

          if (length != arg_len) {
            var arg = [fn].concat([].slice.call(arguments, 0));
            return currie(agent.apply(this, arg), length - arg_len);
          } else {
            return fn.apply(this, arguments);
          }
        };
      }

      var curries = currie(add);
      // Multiple forms of combined calls
      var num1 = curries(1,3)(3)(4)
      var num2 = curries(1,3,3)(4)
      var num3 = curries(1,3)(3)(4)
      console.log(num1,num2,num3);// The print results are all 13.
 

Added by mispris006 on Wed, 09 Oct 2019 12:29:51 +0300