-
-
Notifications
You must be signed in to change notification settings - Fork 355
/
Copy pathmessages.ts
31 lines (28 loc) · 1.18 KB
/
messages.ts
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
import { isArray, isObject } from './utils'
const isNotObjectOrIsArray = (val: unknown) => !isObject(val) || isArray(val)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function deepCopy(src: any, des: any, isRetainExistMessage?: boolean): void {
// src and des should both be objects, and none of them can be a array
if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
throw new Error('Invalid value')
}
const stack = [{ src, des }]
while (stack.length) {
const { src, des } = stack.pop()!
Object.keys(src).forEach(key => {
if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
// replace with src[key] when:
// src[key] or des[key] is not an object, or
// src[key] or des[key] is an array
// if you need to keep the existing message on the i18n instance when merging,
// you do not need to perform the following replacement
if (!isRetainExistMessage || typeof des[key] === 'undefined') {
des[key] = src[key]
}
} else {
// src[key] and des[key] are both objects, merge them
stack.push({ src: src[key], des: des[key] })
}
})
}
}