JSFiddle - React, Tailwind, and code Playground
by kontrach
JavaScript
function brackets(str) {
var arrFromStr = str.replace(/[^\(\{\[\]\}\)]/g, '').split(''),
i = 0,
length = arrFromStr.length,
shifted,
popped;
//if num of brackets isn't even
if (length % 2) {return false}
for (; i < length; i++) {
shifted = arrFromStr.shift();
popped = arrFromStr.pop();
if (/\)\]\}]/.test(shifted)) {return false}
if (shifted === '{') {
if (popped !== '}') {return false}
}
if (shifted === '[') {
if (popped !== ']') {return false}
}
if (shifted === '(') {
if (popped !== ')') {return false}
}
/*
if (shifted === '}'
|| shifted === ']'
|| shifted === ')') {return false}
*/
}
return true;
}
console.log('"" is: ', brackets(''));
console.log('function(){console.log([1,3,{hello: world(1)}])} is: ', brackets('function(){console.log([1,3,{hello: world(1)}])}'));
console.log('{[()]} is: ', brackets('{[()]}'));
console.log('{[()()]} is: ', brackets('{[()()]}'));
console.log('[)({]}) is: ', brackets('[)({]})'));
console.log('[({]})] is: ', brackets('[({]})]'));