Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.