-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergeObject.ts
27 lines (22 loc) · 876 Bytes
/
mergeObject.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
import type { MergeObject, MergeObjectOptions, UnknownObject, Writable } from '@13onthecode/types'
import { toEntries } from '../collocation/toEntries'
import { isObject } from '../guard/isObject'
export function mergeObject<
Target extends UnknownObject,
Source extends UnknownObject,
Options extends MergeObjectOptions
>(
target: Target,
source: Source,
options?: Options
): MergeObject<Target, Source, Options> {
const isDeep = options?.mode === 'deep'
const sourceEntries = toEntries(source)
for (const [sourceKey, sourceValue] of sourceEntries) {
const targetValue = target[sourceKey];
(target as Writable<UnknownObject>)[sourceKey] = isDeep && isObject(targetValue) && isObject(sourceValue)
? mergeObject(targetValue, sourceValue, options)
: sourceValue
}
return target as unknown as MergeObject<Target, Source, Options>
}