Javascript Array reduce() check balanced Parenthesis

Description

Javascript Array reduce() check balanced Parenthesis

function balancedParens( string ) {
    return string.split( '' ).reduce( ( previous, char ) => {
        if ( previous < 0 ) {
            return previous;
        }//from   ww w  . j av  a2 s.  c  o  m
        if ( char === '(' ) {
            return ++previous;
        }

        if ( char === ')' ) {
            return --previous;
        }
    }, 0 );
}

console.log( balancedParens( '((' ) );



PreviousNext

Related