Reduce

Really flexible helper that could potentially re-implement the other helpers (filter, find...etc) to use reduce .

//Problem: Sum the value of an array
//ES5 Solution
var numbers = [10,20,30];
var sum = 0;

for (var i = 0; i<numbers.length; i++){
    sum += numbers [i];
}

console.log(sum) -> 60 

//ES6 Solution
//With reduce we need to pass in an initial value
var sumReduce = numbers.reduce(function(sum, number){
    return sum + n
},0);

//More example:
//We want to take every element, and collect all the value of each 
//We want to end up with an array of [red,yellow,blue]
var primaryColours = [
    {color: 'red'},
    {color: 'yellow'},
    {color: 'blue'}
]

primaryColours.reduce(function(accumulator, primaryColour){
    previous.push(primaryColor.color);
    return previous; 
},[]);

Problem that reduce solves?

Common interview problem:

You are given a string of characters: "() () () ()" and you have to write a function whether or not the parenthesis in this expression are balance. "(((())))", this would also be balance. For any opening one, we have a closing one.

If we have "))))" or "()(((("), these are unbalance

Solve with reduce:

function balanceparents (string) {
    //Turn string into an array: ["(","(","(","("]
    //char in this case represents a single character (Single parenthesis) 
    //Using ! in front of string.split to use javascript to interpret a positive or negative number as false and 0 as true 
    return !string.split("").reduce(function(previous,char){
        if(previous < 0 {return previous;} //To take case such as )( 
        if(char === "(" {return ++ previous;}
        if(char === ")" {return -- previous;}
        return previous; 
    },0); //What is our initial value? We can use a counter, every time we see an opening parenthesis, we increase by one, 
    //Every time we see a closing parenthesis, we decrease by one. 
}

balancedParens("((("); //Expect to return false

Summary:

results matching ""

    No results matching ""