Created
June 11, 2020 15:33
-
-
Save edew/bb6329f49a0a81ed10ee369b20009639 to your computer and use it in GitHub Desktop.
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
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