Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:42
Show Gist options
  • Save rfprod/b43f338cc40cfb73b7c51d5f1857941c to your computer and use it in GitHub Desktop.
Save rfprod/b43f338cc40cfb73b7c51d5f1857941c to your computer and use it in GitHub Desktop.
Braces Validator
function validateBraces(braces) {
const opening = ['(', '{', '['];
const closing = [')', '}', ']'];
if (closing.indexOf(braces[0]) !== -1 || opening.indexOf(braces[braces.length - 1]) !== -1) {
// return if first bracket is closing or last is opening
return false;
}
if (braces.length === 2) {
// return if length is 2 and first and last don't match
if ((braces[0] === opening[0] && braces[1] === closing[0]) ||
(braces[0] === opening[1] && braces[1] === closing[1]) ||
(braces[0] === opening[2] && braces[1] === closing[2])) { return true; }
}
// other cases
while (braces.length > 0 && braces.length % 2 === 0) {
const selectedBrace = braces[0];
const selectedPairIndex = opening.indexOf(braces[0]);
const closingIndexInInput = braces.indexOf(closing[selectedPairIndex]);
/*
* handle symmetry
*/
const left = braces.substring(0, braces.length / 2).split('');
const right = braces.substring(braces.length / 2, braces.length).split('').reverse();
let sym = 0;
if (left.length === right.length) {
loop:
for (let j = 0, jMax = left.length; j < jMax; j++) {
if (opening.indexOf(left[j]) === closing.indexOf(right[j])) { sym++; }
else { break loop; }
}
if (sym === left.length) { return true; }
}
/*
* handle everything else
*/
if (closingIndexInInput === -1 ||
(selectedPairIndex > 0 && (closingIndexInInput - 1) % 2 !== 0)) {
return false;
} else {
braces = braces.slice(1);
braces = (closingIndexInInput < braces.length - 1) ? braces.substring(0, closingIndexInInput - 1) + braces.slice(closingIndexInInput) : braces.substring(0, closingIndexInInput);
if (braces.length % 2 !== 0) { braces = braces.substring(0, braces.length - 1); }
}
}
return (braces.length % 2 !== 0) ? false : true;
}
validateBraces('(){}[]') // true
validateBraces('(}') // false
validateBraces('[(])') // false
validateBraces('([{}])') // true

Braces Validator

Accepts nonempty string consisting on of opening and closing braces: '(', ')', '[', ']', '{', '}'. Returns true if sequence is valid, false is sequence is not valid.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment