Skip to content

Instantly share code, notes, and snippets.

@abm0
Last active August 29, 2015 14:22
Show Gist options
  • Save abm0/ba1c088f96224803197c to your computer and use it in GitHub Desktop.
Save abm0/ba1c088f96224803197c to your computer and use it in GitHub Desktop.
function validate(string) {
if (string[0] == ')') {
console.error(string + ' error: string should start with "("');
return;
}
if (string.length % 2 !== 0) {
console.error(string + ' error: bracket number should be even');
return;
}
var error = false,
length = string.length,
open = 0;
console.log(string + ', length: ' + length);
for (var i = 0; i < length; i++) {
switch (string[i]) {
case '(':
open++;
break;
case ')':
open--;
break;
}
console.log(string[i] + ', open: ' + open);
if (open < 0) {
error = true;
break;
}
}
if (open !== 0) {
error = true;
}
if (error) {
console.error(string + ' error: string is invalid');
} else {
console.info(string + ' success: string is valid');
}
}
var strings = [
'((()()()))', // should be valid
'((()()))()', // should be valid
')(())(',
'()))())',
'((()())())', // should be valid
'((()())',
'()))((',
'((()())())'
];
for (var i in strings) {
console.log('next array: --->');
validate(strings[i]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment