group-show-rule-eval.js
1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* childrenShowRules.result 求值(小程序无 new Function)
* 内置 fallback 解析:valN == '…'、valN != null,多条件用 && 连接
*/
function evalPart(part = '', ctx = {}) {
const trimmed = part.trim()
const eqMatch = trimmed.match(/^val(\d+)\s*==\s*(?:'([^']*)'|"([^"]*)")$/)
if (eqMatch) {
const actual = ctx[`val${eqMatch[1]}`]
const expected = eqMatch[2] != null ? eqMatch[2] : eqMatch[3]
return actual == expected
}
const neNullMatch = trimmed.match(/^val(\d+)\s*!=\s*null$/)
if (neNullMatch) {
const actual = ctx[`val${neNullMatch[1]}`]
return actual != null && actual !== ''
}
return false
}
function fallbackEvaluate(expr = '', ctx = {}) {
if (!expr) return true
return expr.split('&&').every(part => evalPart(part, ctx))
}
function evaluateShowRule(keys = [], resultExpr = '', rowFields = [], getRowFieldValue) {
if (!keys.length || !resultExpr) {
return true
}
try {
const ctx = {}
keys.forEach((key, index) => {
ctx[`val${index + 1}`] = getRowFieldValue(rowFields, key)
})
return fallbackEvaluate(resultExpr, ctx)
} catch (error) {
console.error('[evaluateShowRule] eval error', resultExpr, error)
return false
}
}
export { evaluateShowRule, fallbackEvaluate }
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
evaluateShowRule,
fallbackEvaluate
}
}