Skip to content

Instantly share code, notes, and snippets.

@blackavec
Created February 8, 2018 09:59
Show Gist options
  • Save blackavec/04dcd45d656409c33e3560c9cb9f98f8 to your computer and use it in GitHub Desktop.
Save blackavec/04dcd45d656409c33e3560c9cb9f98f8 to your computer and use it in GitHub Desktop.
/**
* Validate brackets
* write a function that accepts a string and validates braces/brackets/parentheses
* ‘(‘, ‘{‘, ‘[‘ are openers
* ‘)’, ‘}’, ‘]’ closers
* ‘{ [ }’ should return false
* ‘{ [ ] ( ) }’ should return true
**/
const signMap = {
'}': '{',
')': '(',
']': '['
}
const signs = {
'{': 0,
'(': 0,
'[': 0
}
const input = '{[]()}'
const inputArray = input.split('')
for (let i in inputArray) {
const ch = inputArray[i]
const indicator = ch
switch (ch) {
case '(':
case '{':
case '[':
signs[indicator]++
}
switch (ch) {
case ')':
case '}':
case ']':
if (signs[signMap[indicator]] > 0) {
signs[signMap[indicator]]--
} else {
console.log('false')
process.exit()
}
}
}
for (let i in signs) {
if (signs[i] !== 0) {
console.log('false')
process.exit()
}
}
console.log('true')
process.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment