Skip to content

Instantly share code, notes, and snippets.

@aryapreetam
Last active December 20, 2016 16:08
Show Gist options
  • Save aryapreetam/0c0d872b2695dcc84fc0eae414ea2792 to your computer and use it in GitHub Desktop.
Save aryapreetam/0c0d872b2695dcc84fc0eae414ea2792 to your computer and use it in GitHub Desktop.
Simple expression evaluator in javascript
/*
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