JSFiddle - React, Tailwind, and code Playground
by Trevor W
JavaScript
var openDict = {
"(":")",
"{":"}",
"[":"]",
};
// actually did not need this one.
var closedDict = {
")":"(",
"}":"{",
"]":"[",
};
// s *String
function fun(s){
var m = s.replace(/\(|\)|\{|\}|\[|\]/g,"")
if(m !== ""){
return false;
}
var array = [];
for (var i = 0; i < s.length; i++) {
var current = s.substr(i,1);// || var current = s[i];
var last = array[array.length-1];
// Bug was here. indexOf does not work on objects. Same idea though
if (current in openDict){
array[array.length] = current; // || array.push(current);
continue;
}
// Bug was here. I had `openDict[array[last]]`
if (last === -1 || current !== openDict[last]) {
return false;
}
array.pop();
}
return array.length === 0;
}
// Unit Tests
var trueSet = [
"",
"{}",
"{()}",
"{()}[]",
"{({()}[{({()}[{()}[]])}[]])}[]",
];
var falseSet = [
"{",
"{]",
"}{",
"{(})",
"(()",
"{({()}[{({()}[{([)}[]])}[]])}[]",
"{bob}",
];
console.log("True Set");
for (var i = 0; i < trueSet.length;i++){
console.log(i,fun(trueSet[i]));
};
console.log("False Set");
for (var i = 0; i < falseSet.length;i++){
console.log(i,fun(falseSet[i]));
};