application

When I recently added redux to my React project, I used the compose function in Redux to augment the Store.

import {createStore,applyMiddleware,compose} from 'redux';
import createSagaMiddleware from 'redux-saga';
const sagaMiddleware = createSagaMiddleware();
const middlewares = [];

letstoreEnhancers = compose( applyMiddleware(... middlewares,sagaMiddleware), (window && window .devToolsExtension) ? window .devToolsExtension() : (f) = > f,
);

const store = createStore(rootReducer, initialState={} ,storeEnhancers);
Copy the code

The above code allows store to be used with applyMiddleware and DevTools Tension.

The reduce method

Before we get to the compose function, let’s consider what the reduce method is. The official documentation defines the reduce method as follows:

The reduce() method applies a function to each element (left to right) in the accumulator and array, reducing it to a single value.

Take a look at the function signature:

arr.reduce(callback[, initialValue])
Copy the code

Callback executes a function for each value in the array and contains four arguments:

  • accumulator (accumulatorThe accumulator accumulates the return value of the callback; It is the cumulative value returned when the callback was last called, orinitialValue.
  • currentValue (The current value) the element being processed in the array.
  • currentIndexOptional (The current indexThe index of the current element being processed in the array. If initialValue is provided, the index number is 0, otherwise the index is 1.
  • arrayOptional (An array of) calls an array of reduce()
  • initialValueOptional (The initial value) as the first callcallbackThe value of the first argument to If no initial value is provided, the first element in the array is used. Called on an empty array with no initial valuereduceWill be an error.

Here’s a simple 🌰:

Array sum

var sum = [0.1.2.3].reduce(function (a, b) {
  return a + b;
}, 0);
// sum 值为 6
Copy the code

Count the number of occurrences of each element in an array:

var series = ['a1'.'a3'.'a1'.'a5'.'a7'.'a1'.'a3'.'a4'.'a2'.'a1'];

var result= series.reduce(function (accumulator, current) {
    if (current in accumulator) {
        accumulator[current]++;
    }
    else {
        accumulator[current] = 1;
    }
    return accumulator;
}, {});

console.log(JSON.stringify(result));
// {"a1":4,"a3":2,"a5":1,"a7":1,"a4":1,"a2":1}
Copy the code

This example makes clever use of the array reduce method, which is often used in many algorithm interview questions. Note here that you need to specify the initialValue parameter.

Array de-duplication can also be achieved by using the reduce function:

var a = [1.1.2.3.4.4.5.6.6.6.7];
Array.prototype.duplicate = function() {
	return this.reduce(function(cal, cur) {
		if(cal.indexOf(cur) === - 1) {
			cal.push(cur);
		}
		returncal; }}, [])var newArr = a.duplicate();
Copy the code

Compose function

Once you understand the reduce method for arrays, it’s easy to understand the compose function because it’s actually implemented using Reduce. Take a look at the official source code:

export default function compose(. funcs) {
  if (funcs.length === 0) {
    return arg= > arg
  }

  if (funcs.length === 1) {
    return funcs[0]}return funcs.reduce((a, b) = >(... args) => a(b(... args))) }Copy the code

For compose, the return value is a function, and the parameters passed by the compose call will be used as arguments to the last parameter of the compose call.

Look at the following example:

import { compose } 'redux';// function f
const f = (arg) = > ` function f (${arg}) ` 

// function g
const g = (arg) = > ` function g (${arg}) `

// function h The last function can take multiple arguments
const h = (. arg) = > ` function h (${arg.join('_')}) `

console.log(compose(f,g,h)('a'.'b'.'c')) // function f(function g(function h(a_b_c))
Copy the code

Compose (fn1, fn2, fn3) (… args) = > fn1(fn2(fn3(… The args))).

The following is the qr code picture of my official account, welcome to follow.