rulePayloadCanonicalCompare.js
2.04 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import isEqualWith from "lodash/isEqualWith"
/**
* 分账规则缓存对比:排序对象键;再用 isEqualWith 宽松比较叶子,
* 避免 `merchantId`、比例等 number / string 与缓存不一致导致误 bump。
* 数组顺序保持不变(费用类目等顺序有语义)。
*/
function canonicalizeForCompare(val) {
if (val === null || val === undefined) return val
const t = typeof val
if (t !== "object") return val
if (Array.isArray(val)) return val.map((item) => canonicalizeForCompare(item))
const out = {}
Object.keys(val)
.sort()
.forEach((k) => {
const v = val[k]
if (v === undefined) return
out[k] = canonicalizeForCompare(v)
})
return out
}
/**
* 叶子宽松相等:数字与数字字符串、布尔与 "Y"/"N" 等表单与接口常见差异
*/
function looseLeafEqual(val1, val2) {
if (val1 === val2) return true
if (val1 == null && val2 == null) return true
if (val1 == null || val2 == null) return false
const t1 = typeof val1
const t2 = typeof val2
if (t1 === "object" || t2 === "object") return undefined
if (t1 === "boolean" || t2 === "boolean") {
return val1 === val2
}
if (
(t1 === "number" || t1 === "string")
&& (t2 === "number" || t2 === "string")
) {
const s1 = String(val1).trim()
const s2 = String(val2).trim()
if (s1 === "" && s2 === "") return true
const n1 = Number(s1)
const n2 = Number(s2)
if (!Number.isNaN(n1) && !Number.isNaN(n2) && s1 === String(n1) && s2 === String(n2)) {
return n1 === n2
}
return s1 === s2
}
return undefined
}
/**
* @param {object} a
* @param {object} b
* @returns {boolean}
*/
export function financialRulePayloadDeepEqual(a, b) {
if (a === b) return true
try {
const ca = canonicalizeForCompare(a)
const cb = canonicalizeForCompare(b)
return isEqualWith(ca, cb, (v1, v2) => {
const loose = looseLeafEqual(v1, v2)
if (loose === true) return true
if (loose === false) return false
return undefined
})
} catch (e) {
return false
}
}