1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.mergeDeep = void 0;
|
4 | const helpers_js_1 = require("./helpers.js");
|
5 | function mergeDeep(sources, respectPrototype = false, respectArrays = false, respectArrayLength = false) {
|
6 | if (respectArrays && respectArrayLength) {
|
7 | let expectedLength;
|
8 | const areArraysInTheSameLength = sources.every(source => {
|
9 | if (Array.isArray(source)) {
|
10 | if (expectedLength === undefined) {
|
11 | expectedLength = source.length;
|
12 | return true;
|
13 | }
|
14 | else if (expectedLength === source.length) {
|
15 | return true;
|
16 | }
|
17 | }
|
18 | return false;
|
19 | });
|
20 | if (areArraysInTheSameLength) {
|
21 | return new Array(expectedLength).fill(null).map((_, index) => mergeDeep(sources.map(source => source[index]), respectPrototype, respectArrays, respectArrayLength));
|
22 | }
|
23 | }
|
24 | const output = {};
|
25 | if (respectPrototype) {
|
26 | Object.setPrototypeOf(output, Object.create(Object.getPrototypeOf(sources[0])));
|
27 | }
|
28 | for (const source of sources) {
|
29 | if (isObject(source)) {
|
30 | if (respectPrototype) {
|
31 | const outputPrototype = Object.getPrototypeOf(output);
|
32 | const sourcePrototype = Object.getPrototypeOf(source);
|
33 | if (sourcePrototype) {
|
34 | for (const key of Object.getOwnPropertyNames(sourcePrototype)) {
|
35 | const descriptor = Object.getOwnPropertyDescriptor(sourcePrototype, key);
|
36 | if ((0, helpers_js_1.isSome)(descriptor)) {
|
37 | Object.defineProperty(outputPrototype, key, descriptor);
|
38 | }
|
39 | }
|
40 | }
|
41 | }
|
42 | for (const key in source) {
|
43 | if (isObject(source[key])) {
|
44 | if (!(key in output)) {
|
45 | Object.assign(output, { [key]: source[key] });
|
46 | }
|
47 | else {
|
48 | output[key] = mergeDeep([output[key], source[key]], respectPrototype, respectArrays, respectArrayLength);
|
49 | }
|
50 | }
|
51 | else if (respectArrays && Array.isArray(output[key])) {
|
52 | if (Array.isArray(source[key])) {
|
53 | if (respectArrayLength && output[key].length === source[key].length) {
|
54 | output[key] = mergeDeep([output[key], source[key]], respectPrototype, respectArrays, respectArrayLength);
|
55 | }
|
56 | else {
|
57 | output[key].push(...source[key]);
|
58 | }
|
59 | }
|
60 | else {
|
61 | output[key].push(source[key]);
|
62 | }
|
63 | }
|
64 | else {
|
65 | Object.assign(output, { [key]: source[key] });
|
66 | }
|
67 | }
|
68 | }
|
69 | }
|
70 | return output;
|
71 | }
|
72 | exports.mergeDeep = mergeDeep;
|
73 | function isObject(item) {
|
74 | return item && typeof item === 'object' && !Array.isArray(item);
|
75 | }
|