My current 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("()[]{}"));
Requirements for the code to return true:
- Open brackets must be closed by the corresponding type of brackets.
- Open brackets must be closed in the correct sequence.
Issue with my code when tested with "()[]{}"
: it consistently returns [,]
, and I am unsure why. I have attempted regex and ASCII conversions for square brackets without success.