Last active
December 20, 2016 16:08
-
-
Save aryapreetam/0c0d872b2695dcc84fc0eae414ea2792 to your computer and use it in GitHub Desktop.
Simple expression evaluator in javascript
This file contains hidden or 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
| /* | |
| isValid('{{()}}') = true | |
| isValid('{{(]]}') = false | |
| isValid('(({{()}}))') = true | |
| isValid('(({{(}}))') = false | |
| isValid('(({{()()}}))') = true | |
| */ | |
| function isValid(expression){ | |
| let stack = []; | |
| const charMap = new Map().set('{', '}').set('[', ']').set('(', ')'); | |
| for(i=0; i<expression.length; i++){ | |
| let top; | |
| let currentChar = expression[i]; | |
| if(stack.length > 0){ | |
| top = stack[stack.length - 1]; | |
| //console.log("top: ", top, ", currentChar: ", currentChar); | |
| let result = charMap.get(top) === currentChar; | |
| //console.log("isExpressionResolved: ", result); | |
| if(result){ | |
| stack.pop(); | |
| }else{ | |
| stack.push(expression[i]); | |
| } | |
| }else{ | |
| stack.push(expression[i]); | |
| } | |
| } | |
| return stack.length === 0; | |
| } | |
| console.log("isValid('{{()}}'): ", isValid('{{()}}')); | |
| console.log("isValid('{{(]]}'): ", isValid('{{(]]}')); | |
| console.log("isValid('(({{()}}))'): ", isValid('(({{()}}))')); | |
| console.log("isValid('(({{(}}))'): ", isValid('(({{(}}))')); | |
| console.log("isValid('(({{()()}}))'): ", isValid('(({{()()}}))')); | |
| console.log("isValid('}{{()()}}'): ", isValid('}{{()()}}')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment