Redux handwriting method and array reduce method

 

Reduce what to do?

1) summing

2) calculate price

3) consolidated data

4) redux compose the method

 

What are the main contents of this article?

1) describes the main action reduce the

2) reduce handwriting implement the method

 

0) Learn reduce

Before understanding of the benefits of reduce, reduce what we first know that? is a method to reduce array, function takes four parameters, the result of a function, the result of the current index, the array currently executed; at the tail may be added to an initial value. Each parameter has a lot of use, the use of good, may be turned into a variety of changes.

let r = [1,2,3] .reduce ( ( ' on a return value', 'current value', 'current index', 'execution of the array') => { 

}, 'first initial value')

1) summing

This function is performed two times, the first time a = 1, b = 2 ,. at a given time a + b is the result. Second a = 3, b = 3. Operation ended, back in the overall result.

// 求和
let r = [1, 2, 3].reduce((a, b) => {
    return a + b;
})
console.log(r)
// r = 6

2) calculate price

This is the background to traverse pass over the price and quantity, and sometimes the structure is more complex. Here we take a look at the first one, this is wrong. The first 100 * 100 * 2 + 2. The results at a given that the first performance, a.price and a.number can not find, are undefined. So we need an initial value, all the results accumulated in the initial value. Here we look at the second

Function, add the initial value to a 0, that is, reduce the Baga a 0, b so that each result in the accumulation of a. Then the price can be calculated.

// 算价格
let k = [{ price: 100, number: 2 }, { price: 100, number: 2 }, { price: 100, number: 2 }, { price: 100, number: 2 }].reduce((a, b) => {
    return a.price * a.number + b.price * b.number;
})
console.log(k)
// k = NaN
// 算价格
let k = [{ price: 100, number: 2 }, { price: 100, number: 2 }, { price: 100, number: 2 }, { price: 100, number: 2 }].reduce((a, b) => {
    return a + b.price * b.number;
}, 0)
console.log(k)
// k = 800

3) consolidated data

Here is a key and value for an object and traversal key array to an initial value {}, {} assigned to the initial value. So did the combined data

// merge multiple data 

the let Keys = [ 'name', 'Age' ]; 
the let value = [ 'WangShaoQun', '20 is' ]; 


the let obj = keys.reduce ((A, B, index, a curent) = > { 
    A [B] = value [index];
     return A; 
}, {}); 

the console.log (obj); 
// obj = {name: 'WangShaoQun', age: '20 '}

4) redux compose the method

 

First, the creation of the first three methods, the first two will put together a string, converted to uppercase second, third front and rear plus ***

function sum(a, b) {
    return a + b;
}

function toUpper(str) {
    return str.toUpperCase();
}
function add(str) {
    return `***${str}***`
}

Three normal execution method is such that a layer with a layer set, we now have two ways to achieve optimization, one is reduceRight, from right to left to perform. One is reduce, from left to right.

sum(toUpper(add('111','asd')))

Let's look at reduceRight method, let's take a look at the code compose performed (add, toUpper, sum) ( 'wangshao', '666') here is to perform both functions, a function is set with a function. FNS function array receiving layer, inner layer to accept arguments 'wangsaho', '666'. Take a pop function array assigned to a last method lastFn, lastFn as an initial value of reducRight

Then began to traverse from right to left. At this time, a is the initial value, which is the last add function. b is the second, toUpper function. Therefore, the return value is b (a). Is the next value of a toUpper (add ()), b is the sum (). This realization is complete.

function compose(...fns) {
    return function (...args) {
        let lastFn = fns.pop();
        return fns.reduceRight((a, b) => {
            return b(a)
        }, lastFn(...args))
    }
};
let r = compose(add, toUpper, sum)('wangshao', '666');

Then, we will use the above function optimization function at an arrow, the arrow and function may return remove {}. It is reduced to the following code. The effect is the same.

let compose = (...fns) => (...args) => { let lastFn = fns.pop(); return fns.reduceRight((a, b) => b(a), lastFn(...args)) };

Finally, we look redcue method, which we think to light, is the first function nested second function. The results again nested third function. First, the outermost function array FNS is acceptable, the result returned traverse the array, where a, b are the same as above. We return to a function that is the inner function, the parameters have arguments. Is the value of a second toUpper (add (.. args)).

function compose(...fns) {
    return fns.reduce((a, b) => {
        return (...args) => {
            return a(b(...args))
        }
    })
}

The above function with the arrow function optimization look, this is more a brief

let compose = (...fns) => fns.reduce((a, b) => (...args) => a(b(...args)));

 

We saw maybe one method, the first one a year ago redux of the compose method, the second method is now redux of compose

 

Then we continue to reduce handwriting method, add a method to reduce here on a prototype array. Accepts two parameters, one is the callback, one is the initial value of prev. Then start traversing the number is the length of the array, we here on the prototype can use this point to its array of calls. First, we make a judgment as to whether the initial value is null, then the callback is a parameter for the first one, b is a second bit, index = i + 1, compared with the fourth parameter array itself. The value returned is assigned prev, and let i ++; perform a second function, a second go below, callback is the last of a back results prev, b is now an element, index is i, the fourth parameter array itself is unchanged. The overall result back to prev. We can see, here I would like to use forEach to achieve. But it seems that will not change the number of traverse and index. So the most original or use it for recycling.

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);  
        }
    }
    // this.forEach((e, i) => {
    //     if (prev == undefined) {
    //         console.log(e,e+1)
    //         prev = callback(e,e+1, i + 1, this);
    //     } else {
    //         prev = callback(prev,e+1 , i+1, this);
    //     }
    // })
    return prev;
};


let r = [1, 2, 3].reduce((a, b, index, current) => {
    return a + b
})

 

 

What's that strange place, discuss with each other, to learn. Thank you

Guess you like

Origin www.cnblogs.com/At867604340/p/12523308.html