如何将一个长布尔查询字符串分割成多个小布尔查询



我有一个很长的布尔表达式,需要分成多个小布尔表达式。例如:

原始表达:1 或 (2 和 3( 和(不是 4 或 5(或 (6 和 (7 或 8 或 (9 和 10(((

表情1:1 表达式 2:2 和 3,而不是 4 表达式 3:2 和 3 和 5 表达式 4:6 和 7 表达式 5:6 和 8 表达式6:6、9和10

如果我正在计算(表达式 1 或表达式 2 或表达式 3 或表达式 4 或表达式 5 或表达式 6(,那么我得到的是我的原始表达式。

实际上,我的表达式最多包含 10000 个字符,具有非常复杂和嵌套的布尔表达式。有什么建议或想法吗?

看起来您要做的是将查询转换为析取范式。原则上不难做到(解析为 AST,然后根据链接应用等式(,但问题是 DNF 表示的大小可以呈指数级增长。因此,对于 10k 个字符的任意表达式,您根本无法这样做(您将耗尽时间和内存(。

如果可以使用变量,则可以将表达式的某些部分重构为变量,然后在表达式中使用这些变量。下面是一个示例

// initial complex boolean expression
const x = "blah";
if (x === "asdfasd" || (x !== "asdfasd" && x.length < 4)) {
// match
}
// save parts of the complex boolean expression into variables
const isCondition1 = x === "asdfasd";
const isCondition2 = x !== "asdfasd";
const isCondition3 = x.length < 4;
// use those variable
if (isCondition1 || (isCondition2 && isCondition3)) {
// match
}
// use the variables to continue simplifying the expression
const isCondition4 = isCondition2 && isCondition3;
if (isCondition1 || isCondition4) {
// match
}
// until you are left with one expression
const isCondition5 = isCondition1 || isCondition4;
if (isCondition5) {
// match
}

所以

if (x === "asdfasd" || (x !== "asdfasd" && x.length < 4)) {
// match
}

可以重写为

const isCondition1 = x === "asdfasd";
const isCondition2 = x !== "asdfasd";
const isCondition3 = x.length < 4;
const isCondition4 = isCondition2 && isCondition3;
const isCondition5 = isCondition1 || isCondition4;
if (isCondition5) {
// match
}

我还会将这些表达式移动到函数中,并将这些函数组织在单独的文件夹/文件中。

isCondition1.js

module.exports = x => x === "asdfasd";

isCondition2.js

module.exports = x => x !== "asdfasd";

isCondition3.js

module.exports = x => x.length < 4;

isCondition4.js

const isCondition2 = require("isCondition2");
const isCondition3 = require("isCondition3");
module.exports = x => isCondition2(x) && isCondition3(x);

isCondition5.js

const isCondition1 = require("isCondition1");
const isCondition4 = require("isCondition4");
module.exports = x => isCondition1(x) || isCondition4(x);

索引.js

const isCondition5 = require("isCondition5");
if (isCondition5(x)) {
// match
}

最新更新