Reputation: 1480
I saw one interview question .(i.e)
I have one array inside a function
function validate(){
var array=["(","{","[","]","}",")"];
}
Also i have one input field with submit button
<body>
<input type="text" name="equation" id="equation">
<input type="submit" name="check" value="check" onclick="validate();">
</body>
Now my doubt is when I enter input data as {()}
it should display valid data in an alert.When I enter input data like {()}]
it should display as invalid data.Which means for unbalanced input it should display invalid
message.For that I need to compare array elements within an array.
How to do it?
Upvotes: 0
Views: 69
Reputation: 386883
You could save the opened brackets and delete the last if the corespondent bracket is found. At last, check if the open bracket array is empty.
function validate(s) {
var open = [],
brackets = { '(': 1, '{': 2, '[': 3, ']': -3, '}': -2, ')': -1 };
return s.split('').every(function (a) {
if (!brackets[a]) {
return true;
}
if (brackets[a] > 0) {
open.push(-brackets[a]);
return true;
}
if (open[open.length - 1] === brackets[a] ) {
open.pop();
return true;
}
}) && open.length === 0;
}
console.log(validate('([()()])'));
console.log(validate('(a+2)*4'));
console.log(validate(']'));
Upvotes: 1