Created
August 19, 2018 03:35
-
-
Save davidraedev/f72f3fa9d8a62ed2d14d4398398d015d to your computer and use it in GitHub Desktop.
check if a string has balanced brackets (or configurable delimiters)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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