JSFiddle - React, Tailwind, and code Playground
by Jason Green
JavaScript
// [(dfg)] => true
// ()() => true
// )( => false
// ()( => false
// ()) => false
// ([) => false
function isBalanced(str) {
const a = [];
let m = {
'[': ']',
'(': ')',
'{': '}'
};
for (let i = 0; i < str.length; i++) {
const character = str[i];
if (m.hasOwnProperty(character)) {
// opening bracket
a.push(character);
}
const x = Object.values(m).find(v => v === character);
if (x && a.length === 0) {
return false;
}
if (m[a[a.length - 1]] === x) {
a.pop();
}
//console.log(a);
}
return (a.length === 0);
}
console.log('())', isBalanced('())'))
console.log('(df[g)', isBalanced('(df[g)'))
console.log('()([])', isBalanced('()([])'))
console.log(')(', isBalanced(')('))