Created
April 28, 2019 07:29
Star
You must be signed in to star a gist
This file contains 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
let input = '[{}]' | |
let input2 = '[[{}]()]' | |
let input3 = '[{})[]' | |
function isOk (inputString) { | |
let arr = inputString.split(''); | |
let stack = [] | |
for (let i = 0; i < arr.length; i++) { | |
if (['[', '{', '('].includes(arr[i])) { | |
stack.push(arr[i]) | |
} else if ([')', ']', '}'].includes(arr[i])) { | |
let lastOne = stack.pop() | |
if (!lastOne) { | |
throw new Error('invalid syntax'); | |
} | |
if (arr[i] === '}' && lastOne !== '{') { | |
throw new Error('invalid syntax'); | |
} | |
if (arr[i] === ']' && lastOne !== '[') { | |
throw new Error('invalid syntax'); | |
} | |
if (arr[i] === ')' && lastOne !== '(') { | |
throw new Error('invalid syntax'); | |
} | |
// if lastOne was empty it's a | |
} | |
} | |
if (stack.length !== 0) { | |
throw new Error ('invalid syntax'); | |
} | |
console.log(inputString, ' : OK') | |
} | |
try { | |
isOk(input3); | |
} catch (e) { | |
console.log(input3, ' : ERR:', e); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment