Skip to content

Instantly share code, notes, and snippets.

@davidraedev
Created August 19, 2018 03:35
Show Gist options
  • Save davidraedev/f72f3fa9d8a62ed2d14d4398398d015d to your computer and use it in GitHub Desktop.
Save davidraedev/f72f3fa9d8a62ed2d14d4398398d015d to your computer and use it in GitHub Desktop.
check if a string has balanced brackets (or configurable delimiters)
function isBalanced( string, opening_char = "[", closing_char = "]" ) {
let openings = 0;
for ( let pos = 0; pos < string.length; pos++ ) {
let char = string[ pos ];
// if opening, store that info
if ( char === opening_char ) {
openings++;
}
else if ( char === closing_char ) {
// if we have no openings, is not balanced
if ( openings === 0 ) {
return false;
}
// remove the last opening
else {
openings--;
}
}
}
// if we have any leftover openings, is not balanced
if ( openings !== 0 ) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment