Skip to content

Instantly share code, notes, and snippets.

@shekohex
Last active July 7, 2019 04:50
Show Gist options
  • Save shekohex/747440edb1e45810f368cc241e1436c5 to your computer and use it in GitHub Desktop.
Save shekohex/747440edb1e45810f368cc241e1436c5 to your computer and use it in GitHub Desktop.
/// https://leetcode.com/problems/parsing-a-boolean-expression
/**
* @param {string} expression
* @return {boolean}
*/
var parseBoolExpr = function(expression) {
const stack = [];
for (let i = 0; i <= expression.length; ++i) {
const c = expression[i];
if (c === '(' || c === ',') continue;
if (c === '!') stack.push(not);
else if (c === '&') stack.push(and);
else if (c === '|') stack.push(or);
else if (c === 't') stack.push(true);
else if (c === 'f') stack.push(false);
else if (c === ')') {
const params = [];
while (typeof stack[stack.length - 1] === 'boolean') {
params.push(stack.pop());
}
const func = stack.pop();
stack.push(func(params));
}
}
return stack[stack.length - 1];
};
const not = xs => !xs[0];
const or = xs => xs.some(x => x);
const and = xs => xs.every(x => x);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment