I am currently designing a GUI that allows the user to define some logic. I don’t want it getting too complex, so I am limiting it to a single set of brackets. So, the idea is to check that between the opening and closing brackets there are not any other opening brackets.
eg. IF ( a + b OR **(** b+ c) would alert with error.
So I decided with the route of:
- Find the first open bracket
- Find the first close bracket
- Using those indices search between and find any open brackets
- If any open brackets are found display an error
- Continue the loop for any other logic
Here’s the code. I think its pretty horrific and I am sure there must be a better way to do this. Some kind of IndexOf maybe.
<select rel="OpenBracket" id="open1">
<option value=""></option>
<option value="(">(</option>
</select>
Some True/Fale here
<select rel="CloseBracket" id="close1">
<option value=""></option>
<option value=")">)</option>
</select>
AND
<br />
<select rel="OpenBracket" id="open2">
<option value=""></option>
<option value="(">(</option>
</select>
Some True/Fale here
<select rel="CloseBracket" id="close2">
<option value=""></option>
<option value=")">)</option>
</select>
<button onclick="javascript:TestingRules();">Check</button>
function GetOpenBrackets() {
var openBracketArray = [];
jQuery('[rel="OpenBracket"]').each(function() {
if (jQuery(this).val() == "(") {
openBracketArray.push(jQuery(this).attr('id'));
} else {
openBracketArray.push(jQuery(this).val());
}
});
return openBracketArray;
}
function GetCloseBrackets() {
var closeBracketArray = [];
jQuery('[rel="CloseBracket"]').each(function() {
if (jQuery(this).val() == "(") {
closeBracketArray.push(jQuery(this).attr('id'));
} else {
closeBracketArray.push(jQuery(this).val());
}
});
return closeBracketArray;
}
function TestingRules() {
var openBrackets = GetOpenBrackets();
var closeBrackets = GetCloseBrackets();
var closeBracketIndex;
var openBracketIndex;
for (openBracketIndex in openBrackets) {
if (openBrackets[openBracketIndex] !== "") {
var foundCloseBracketIndex = -1;
for (closeBracketIndex in closeBrackets) {
if (openBracketIndex <= closeBracketIndex) {
if (closeBrackets[closeBracketIndex] !== "") {
foundCloseBracketIndex = closeBracketIndex;
break;
}
}
}
if (foundCloseBracketIndex > -1) {
var openBracketCheck;
for (openBracketCheck in openBrackets) {
if (openBracketIndex < openBracketCheck && closeBracketIndex >= openBracketCheck) {
if (openBrackets[openBracketCheck] !== "") {
alert('error');
}
}
}
}
}
}
// for testing:
// console.log(OpenBracketArray.length);
}
Why not just keep a counter, or count paren stack depth? If you inc for open parens, dec for closing, and the counter goes above 1, you have an error. (If I’ve understood your requirements correctly.)