/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see .
*/
import { TypedArray } from '@theqrl/web3-types';
import { isNullish } from '@theqrl/web3-validator';
const isIterable = (item: unknown): item is Record =>
typeof item === 'object' &&
!isNullish(item) &&
!Array.isArray(item) &&
!(item instanceof TypedArray);
// The following code is a derivative work of the code from the "LiskHQ/lisk-sdk" project,
// which is licensed under Apache version 2.
/**
* Deep merge two objects.
* @param destination - The destination object.
* @param sources - An array of source objects.
* @returns - The merged object.
*/
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
export const mergeDeep = (
destination: Record,
...sources: Record[]
): Record => {
if (!isIterable(destination)) {
return destination;
}
const result = { ...destination };
for (const src of sources) {
// eslint-disable-next-line no-restricted-syntax
for (const key in src) {
if (FORBIDDEN_KEYS.has(key) || !Object.hasOwnProperty.call(src, key)) {
continue;
}
if (isIterable(src[key])) {
if (!result[key]) {
result[key] = {};
}
result[key] = mergeDeep(
result[key] as Record,
src[key] as Record,
);
} else if (!isNullish(src[key])) {
if (Array.isArray(src[key]) || src[key] instanceof TypedArray) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
result[key] = (src[key] as unknown[]).slice(0);
} else {
result[key] = src[key];
}
}
}
}
return result;
};