JSFiddle - React, Tailwind, and code Playground
by Jake Overall
JavaScript
/*
Write a function that takes in a string and can evaulate each type of brackets to determine if there are matching pairs. Return true if all opening brackets have a closing or return false if they do not.
*/
var strPass = '({}[]{[]})';
var strFail = '({{{]}})';
var compare = function (str) {
str = str.split('');
var broken = false;
str.forEach(function (value, i) {
if (value === '{') {
if (str.indexOf('}') === -1) {
broken = true;
} else {
str.splice(i, 1);
str.splice(str.indexOf('}'), 1);
}
} else if (value === '[') {
if (str.indexOf(']') === -1) {
broken = true;
} else {
str.splice(i, 1);
str.splice(str.indexOf(']'), 1);
}
} else if (value === '(') {
if (str.indexOf(')') === -1) {
broken = true;
} else {
str.splice(i, 1);
str.splice(str.indexOf(')'), 1);
}
}
})
if (broken) {
return false
} else {
return true
}
}
compare(strPass);
compare(strFail);