-
-
Save zhujinxuan/ba317a416282fb630d12e9b0eeb2078c to your computer and use it in GitHub Desktop.
validate with some parenthesis
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
"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