Skip to content

Instantly share code, notes, and snippets.

@zhujinxuan
Created October 17, 2017 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhujinxuan/ba317a416282fb630d12e9b0eeb2078c to your computer and use it in GitHub Desktop.
Save zhujinxuan/ba317a416282fb630d12e9b0eeb2078c to your computer and use it in GitHub Desktop.
validate with some parenthesis
"use strict";
function evaluate(expression) {
let neatExpr = expr2Array(expression);
let rightInd = evaluateNeat(neatExpr, 1);
return rightInd === neatExpr.length - 1;
}
function expr2Array(expression) {
let newExpr = expression.replace(/\(/g, " ( ").replace(/\)/g, " ) ");
let neatExpr = newExpr.split(" ").filter(xstr => xstr !== "");
return ["(", ...neatExpr, ")"];
}
function evaluateNeat(expr, indLeft) {
if (expr.length === 0) return false;
let cache = [];
for (let ind = indLeft; ind < expr.length;) {
if (expr[ind] === ")") {
if (validate(cache)) {
return ind;
}
return expr.length;
}
if (expr[ind] === "(") {
let nextInd = evaluateNeat(expr, ind + 1);
if (nextInd < expr.length) {
ind = nextInd + 1;
cache.push("1");
continue;
} else {
return expr.length;
}
}
cache.push(expr[ind]);
ind++;
}
return expr.length;
}
function validate(expr) {
let shallNumber = true;
for (const elem of expr) {
if (shallNumber) {
if (!isNumber(elem)) {
return false;
}
shallNumber = false;
} else {
if (!isLogical(elem)) {
return false;
}
shallNumber = true;
}
}
return shallNumber === false;
}
function isNumber(x) {
return parseInt(x) + "" === x;
}
function isLogical(x) {
return ["and", "or"].indexOf(x) > -1;
}
console.log("Shall be false");
console.log(evaluate(""));
console.log(evaluate("()"));
console.log(evaluate("1 and 2)"));
console.log(evaluate("or 1 and 2"));
console.log(evaluate(" 1 and 2 or"));
console.log(evaluate("((1 and 2) or (((3 and 4))) or 6"));
console.log("Shall be true");
console.log(evaluate("1"));
console.log(evaluate("1 and 2"));
console.log(evaluate("1 and 2 or 3"));
console.log(evaluate("(5 and 2)"));
console.log(evaluate("(5 and 2) or 3"));
console.log(evaluate("(1 and 2) or (3 and 4)"));
console.log(evaluate("(1 and 2) or (3 and 4) or 6"));
console.log(evaluate("(1 and 2) or (((3 and 4))) or 6"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment