Detailed explanation of the usage of compose function and pipe function in JS

Detailed explanation of the usage of compose function and pipe function in JS

compose function

The compose function can flatten functions that need to be executed in nested order. Nested execution means that the return value of one function will be used as the parameter of another function. Let's consider a simple requirement: This requirement is very simple, and a calculation function will do:

const calculate = x => (x + 10) * 10;
let res = calculate(10);
console.log(res); // 200

But according to the functional programming we talked about before, we can break down the complex steps into several simple and reusable steps, so we broke out an addition function and a multiplication function:

const add = x => x + 10;
const multiply = x => x * 10;

// Our calculation is changed to a nested calculation of two functions, and the return value of the add function is used as the parameter of the multiply function let res = multiply(add(10));
console.log(res); // The result is still 200

The calculation method above is the nested execution of functions, and the role of our compose is to flatten the nested execution methods as parameters. When nested execution occurs, the method inside, that is, the method on the right, is executed first, and then returns to the left. Our compose method also starts from the parameter on the right, so our goal is very clear. We need a compose method like this:

// Parameters are executed from right to left, so multiply comes first and add comes last let res = compose(multiply, add)(10);

Before we talk about this, let's take a look at a function we need to use: Array.prototype.reduce

Array.prototype.reduce

The reduce method of an array can achieve an accumulation effect. It receives two parameters, the first is an accumulator method, and the second is the initialization value. The accumulator receives four parameters. The first one is the last calculated value, and the second one is the current value of the array. These two parameters are mainly used. The last two parameters are not commonly used. They are the current index and the array of the current iteration:

const arr = [[1, 2], [3, 4], [5, 6]];
// The initial value of prevRes is the passed [], and it will be the value calculated after each iteration const flatArr = arr.reduce((prevRes, item) => prevRes.concat(item), []);

console.log(flatArr); // [1, 2, 3, 4, 5, 6]

Array.prototype.reduceRight

Array.prototype.reduce will iterate from left to right. If you need to iterate from right to left, use Array.prototype.reduceRight.

const arr = [[1, 2], [3, 4], [5, 6]];
// The initial value of prevRes is the passed [], and it will be the value calculated after each iteration const flatArr = arr.reduceRight((prevRes, item) => prevRes.concat(item), []);

console.log(flatArr); // [5, 6, 3, 4, 1, 2]

So how do we implement this compose method? We need to use Array.prototype.reduceRight:

const compose = function(){
  // Store the received parameters into an array, args == [multiply, add]
  const args = [].slice.apply(arguments);
  return function(x) {
    return args.reduceRight((res, cb) => cb(res), x);
  }
}

// Let's verify this method let calculate = compose(multiply, add);
let res = calculate(10);
console.log(res); // The result is still 200

The compose function above would be more concise using ES6:

const compose = (...args) => x => args.reduceRight((res, cb) => cb(res), x);

Redux's middleware is implemented using compose, and the loading order of loader in webpack is also from right to left, because it is also implemented using compose.

pipe Function

The pipe function is the same as the compose function, and the parameters are also laid out flatly, but the order is from left to right. Let's implement it. Just change reduceRight to reduce:

const pipe = function(){
  const args = [].slice.apply(arguments);
  return function(x) {
    return args.reduce((res, cb) => cb(res), x);
  }
}

// Change the order of parameters to from left to right let calculate = pipe(add, multiply);
let res = calculate(10);
console.log(res); // The result is still 200

ES6 writing:

const pipe = (...args) => x => args.reduce((res, cb) => cb(res), x)

The above is a detailed explanation of the usage of the compose function and pipe function in JS. For more information about JS, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Node.js pipe implements source code parsing
  • Understand the principles and implementation of nodejs's stream and pipe mechanisms
  • Detailed explanation of JavaScript Reduce
  • Detailed explanation of JavaScript Array.reduce source code
  • 5 Basic Usage Examples of reduce() in JavaScript
  • Analysis of the principle and usage skills of JS array reduce() method
  • Detailed explanation of the function and usage of JS array Reduce method
  • Example analysis of the usage of JS array method reduce
  • JavaScript reduce and reduceRight explained

<<:  Solve the problem that VMWare cannot display in full screen after installing Mac system

>>:  8 examples of using killall command to terminate processes in Linux

Recommend

19 MySQL optimization methods in database management

After MySQL database optimization, not only can t...

Mysql sorting and paging (order by & limit) and existing pitfalls

Sorting query (order by) In e-commerce: We want t...

CSS uses BEM naming convention practice

When you see a class, what information do you wan...

A brief discussion on several advantages of Vue3

Table of contents 1. Source code 1.1 Monorepo 1.2...

Analysis of MySQL example DTID master-slave principle

Table of contents 1. Basic Concepts of GTID 2. GT...

How to migrate sqlite to mysql script

Without further ado, I will post the code for you...

How to use TypeScript in Vue

introduction In recent years, the call for TypeSc...

Web developers are concerned about the coexistence of IE7 and IE8

I installed IE8 today. When I went to the Microso...

MYSQL's 10 classic optimization cases and scenarios

Table of contents 1. General steps for SQL optimi...

VUE+Canvas realizes the whole process of a simple Gobang game

Preface In terms of layout, Gobang is much simple...

How to communicate between WIN10 system and Docker internal container IP

1. After installing the Windows version of Docker...