Regular study notes, including ES6, Promise, Node.js, Webpack, HTTP Principles, Vue buckets, and possibly more Typescript, Vue3, and common interview questions.

reduce

let r = [1.2.3.4.5].reduce((total, num) = > {
    return total + num
})
console.log(r);
Copy the code

The reduce() method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually evaluates to a value.

Reduce () can be used as a higher-order function for compose of functions.

(note:reduce()No callbacks are executed for empty arrays.

In simple terms, reduce takes a function whose first loop passes in the first two items of the array, performs the corresponding calculation, and returns the result. Each subsequent loop passes the result of the previous loop to the first parameter.

initialValue

InitialValue, the second argument to reduce(), represents the initialValue passed to the function.

We can use it to calculate the total price of the shopping cart

let r = [{price: 100.count: 1}, {price: 200.count: 2}, {price: 300.count: 3}].reduce((total, num) = > {
    return total + num.price * num.count
}, 0)
console.log(r); / / 1400
Copy the code

So our default first entry for the entire array is 0, which is great for dealing with non-numeric arrays like this.

currentIndex

CurrentIndex, the third argument to reduce(), represents the index of the current element.

We can use it to combine multiple data into one.

let keys = ['name'.'age'];
let values = ['mxs'.18];
let obj = keys.reduce((memo, cur, index) = > {
  memo[cur] = values[index]
  return memo
}, {});
console.log(obj); // {name: 'mxs', age: 18}
Copy the code

Simulate the compose function logic

Compose function, function call flat. The operation of passing the result of one function as an argument to the next makes complex function calls look cleaner.

Suppose we now need to implement such a feature

Take two strings, concatenate them, convert them to uppercase, and finally add special characters and display them.

This is how we might solve the problem.

let str1 = 'mxs'
let str2 = 'nb'
function sum(a, b) {
    return a + b
}
function toUpper(str) {
    return str.toUpperCase()
}
function add(str) {
    return '* * *' + str + '* * *'
} 
console.log(add(toUpper(sum(str1, str2)))) // ***MXSNB***
Copy the code

We only simulated three functions, and the code was already cumbersome.

To simplify this tedious code, we can use the compose function to process it.

function compose(. fns) {
  return function (. args) {
  let fn = fns.shift();
    return fns.reduce((a, b) = > {
      returnb(a) }, fn(... args)) } }let r = compose(sum, toUpper, add)(str1, str2)
console.log(r); // ***MXSNB***
Copy the code

We wrap the closure with a method called the compose function, which makes the output code look cleaner and logical.

You can use the arrow function to simplify the compose function code

let compose = (. fns) = > (. args) = > {
    let fn = fns.shift();
    return fns.reduce((a, b) = >b(a), fn(... args)) }Copy the code

At the same time, we can also simplify the idea of implementation.

function compose(. fns) {
  return fns.reduceRight((a, b) = > {
    return (. args) = > {
      returna(b(... args)) } }) }Copy the code

This implementation is hard to understand, but easy to explain, so take a moment to look at it in private.

Then we’ll simplify it and end up with something like this.

let compose = (. fns) = > fns.reduceRight((a, b) = > (. args) = >a(b(... args)))Copy the code

You end up with a line of code.

This line of code is also used in the Redux source code.

Handwriting to Reduce

Array.prototype.reduce = function (callBack, prev) {
  for (let i = 0; i < this.length; i++) {
    if (prev == undefined) {
      prev = callBack(this[i], this[i + 1], i + 1.this);
      i++;
    } else {
      prev = callBack(prev, this[i], i, this)}}return prev
}
let r = [1.2.3].reduce((a, b, index, current) = > a + b)
let r2 = [1.2.3].reduce((a, b, index, current) = > a + b, 100)
console.log(r); / / 6
console.log(r2); / / 106
Copy the code

The idea is to loop through the array, execute the function and print the result. If there is a second parameter, the second parameter is processed. If not, directly perform output processing.

map

Loop through each item, process each item in the array, and then return the result as a new array without changing the original array.

let arr = [1.2.3]
let newArr = arr.map(item= > item * 2);
console.log(newArr, arr) // [2, 4, 6] [1, 2, 3]
Copy the code

filter

Filter the array, filter out the items with a result of false, and return the result.

let arr = [1.2.3]
let newArr = arr.filter(item= >item ! =2);
console.log(newArr, arr) // [1, 3] [1, 2, 3]
Copy the code

some

Checks to see if there is a result in the current array that matches the output criteria, and prints true if there is, and false if not. This method is the opposite of the every method

let arr = [1.2.3]
let newArr = arr.some(item= > item == 2);
console.log(newArr) // true 
Copy the code

every

Check to see if there is a result in the current array that is inconsistent with the output criteria, and print true if there is, and false if not. This method is the opposite of some

let arr = [1.2.3]
let newArr = arr.every(item= > item == 2);
console.log(newArr) // false 
Copy the code

find

Find the result of the array that matches the condition of the function and return it. If not found, undefined is returned

let arr = [1.2.3]
let newArr = arr.find(item= > item == 2);
console.log(newArr) / / 2
Copy the code

includes

Returns true if the array contains the function condition, false if not

let r = [1.2.3].includes(2)
console.log(r); // true
Copy the code

This article was created by Mo Xiaoshang. If there are any problems or omissions in the article, welcome your correction and communication. You can also follow my personal site, blog park and nuggets, AND I will upload the article to these platforms after it is produced. Thank you for your support!