-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset-or-delete.js
111 lines (107 loc) · 2.89 KB
/
set-or-delete.js
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const cloneDeep = require("lodash/cloneDeep")
function sameKeys(dstKeys, srcKeys) {
// keys are from an array so they are in order
if (dstKeys.length !== srcKeys.length) return false
for (let i = 0; i < dstKeys.length; i++) {
if (dstKeys[i] !== srcKeys[i]) {
return false
}
}
return true
}
function stringify(obj, key) {
const value = obj[key]
if (typeof value === "undefined" && !Object.keys(obj).includes(key))
return "not-present"
if (typeof value === "function") return (value.name || "unnamed") + "()"
return JSON.stringify(value, null, 2)
}
function setOrDeleteKeyWithMessages(dst, src, messages, keyPath, key) {
if (
typeof dst[key] === "object" &&
typeof src[key] === "object" &&
dst[key] !== null &&
src[key] !== null
)
setOrDeleteWithMessages(dst[key], src[key], messages, keyPath)
else {
if (typeof src[key] === "object" && src[key] !== null) {
if (messages)
messages.push(
`${keyPath}: changing ${stringify(dst, key)} to ${stringify(
src,
key
)}`
)
dst[key] = cloneDeep(src[key])
} else if (dst[key] !== src[key]) {
if (messages)
messages.push(
`${keyPath}: changing ${stringify(dst, key)} to ${stringify(
src,
key
)}`
)
dst[key] = src[key]
}
}
}
export default function setOrDeleteWithMessages(dst, src, messages, keyPath) {
if (
typeof dst === "object" &&
typeof src === "object" &&
dst !== null &&
src !== null
) {
const dstKeys = Object.keys(dst)
const srcKeys = Object.keys(src)
if (Array.isArray(dst) && Array.isArray(src)) {
for (const key of srcKeys)
setOrDeleteKeyWithMessages(
dst,
src,
messages,
`${keyPath ? keyPath : ""}[${key}]`,
key
)
if (!sameKeys(dstKeys, srcKeys)) {
for (const key of dstKeys.reverse()) {
// reverse because splice changes order each time
if (srcKeys.includes(key)) continue
else {
if (messages)
messages.push(
`deleting ${keyPath ? keyPath : ""}[${key}]: ${dst[key]}`
)
dst.splice(key, 1)
}
}
return
}
} else {
for (const key of srcKeys) {
if (typeof src[key] === "undefined") {
if (messages)
messages.push(
`deleting ${keyPath ? keyPath + "." : ""}${key}: ${dst[key]}`
)
delete dst[key]
} else
setOrDeleteKeyWithMessages(
dst,
src,
messages,
(keyPath ? keyPath + "." : "") + key,
key
)
}
}
} else {
if (messages)
messages.push(
`${
keyPath ? keyPath + ": c" : "C"
}an not change type ${typeof dst} to ${typeof src}`
)
}
}