Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why reduce() skip square brackets?

I have this code:

var isValid = function(s) {
    let arr = [...s];

    arr.reduce((acc, cur) => {
        console.log(`arr in reduce: ${arr}`);
        console.log(`acc: ${acc}`);
        console.log(`cur: ${cur}`);
        if ((acc && cur)
        && (
            (acc === '(' && cur === ')')
            || (acc === '{' && cur === '}')
            || (acc === '[' && cur === ']')
        )) {
            arr.splice(arr.indexOf(acc), 2);
            console.log(`arr after splice: ${arr}`);
            return arr;
        }
        else {
            console.log(`else statement: ${cur}`);
            return cur;
        }
    });

    return arr.length === 0 ? true : false;
};

console.log(isValid("()[]{}"));

It needs to return true if:

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.

My code doesn't pass this test "()[]{}": it always returns [,] and I don't understand why. I've tried using regex, anscii for the square brackets but it doesn't work.

like image 320
Viet Avatar asked Feb 24 '26 13:02

Viet


1 Answers

You could take an object for the expected closing characters and if an open character is found push the expected closing character to a stack.

Otherwise check the popped value against the character.

var isValid = function([...array]) {
        var stack = [],
            open =  { '(': ')', '[': ']', '{': '}' };
        return array.every(c => c in open ? stack.push(open[c]) : c === stack.pop())
            && !stack.length;
    };

console.log(isValid("()[]{}"));
console.log(isValid("(({}[()]))[]{}"));
console.log(isValid("()[]{}}"));
console.log(isValid("["));
like image 159
Nina Scholz Avatar answered Feb 27 '26 03:02

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!