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:
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.
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("["));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With