I'm wrote a simple function isBalanced
which takes some code and returns true
if the brackets in the code are balanced and false
otherwise:
function isBalanced(code) {
var length = code.length;
var delimiter = '';
var bracket = [];
var matching = {
')': '(',
']': '[',
'}': '{'
};
for (var i = 0; i < length; i++) {
var char = code.charAt(i);
switch (char) {
case '"':
case "'":
if (delimiter)
if (char === delimiter)
delimiter = '';
else delimiter = char;
break;
case '/':
var lookahead = code.charAt(++i);
switch (lookahead) {
case '/':
case '*':
delimiter = lookahead;
}
break;
case '*':
if (delimiter === '*' && code.charAt(++i) === '/') delimiter = '';
break;
case '\n':
if (delimiter === '/') delimiter = '';
break;
case '\\':
switch (delimiter) {
case '"':
case "'":
i++;
}
break;
case '(':
case '[':
case '{':
if (!delimiter) bracket.push(char);
break;
case ')':
case ']':
case '}':
if (!delimiter && bracket.length && matching[char] !== bracket.pop())
return false;
}
}
return bracket.length ? false : true;
}
The function must not operate on brackets inside strings and comments. I wanted to know if my current implementation will work correctly for all test cases. I also wanted to know whether brackets may be used in any other context beside strings and comments in a language like JavaScript (AFAIK this is not the case).