Skip to content

Instantly share code, notes, and snippets.

@edew
Created June 11, 2020 15:33
Show Gist options
  • Save edew/bb6329f49a0a81ed10ee369b20009639 to your computer and use it in GitHub Desktop.
Save edew/bb6329f49a0a81ed10ee369b20009639 to your computer and use it in GitHub Desktop.
console.clear()
const OPEN_ROUND = '('
const CLOSE_ROUND = ')'
const OPEN_CURLY = '{'
const CLOSE_CURLY = '}'
const OPEN_SQUARE = '['
const CLOSE_SQUARE = ']'
const closes = (open, close) => {
if (open === OPEN_ROUND && close === CLOSE_ROUND) {
return true
}
if (open === OPEN_CURLY && close === CLOSE_CURLY) {
return true
}
if (open === OPEN_SQUARE && close === CLOSE_SQUARE) {
return true
}
return false
}
const isBalanced = (string) => {
const stack = []
for (let i = 0; i < string.length; i++) {
const character = string[i]
switch (character) {
case OPEN_ROUND:
case OPEN_CURLY:
case OPEN_SQUARE:
stack.push(character)
break
case CLOSE_ROUND:
case CLOSE_CURLY:
case CLOSE_SQUARE:
const popped = stack.pop()
if (stack.length === 0 && !closes(popped, character)) {
return false
}
break
default:
throw new Error('Unexpected character: ' + character)
}
}
return true
}
['[[]]', '()', ')()', '[[(])]'].forEach(string => { console.log(isBalanced(string)) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment