| 1 | 'use strict';
|
|---|
| 2 |
|
|---|
| 3 | Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|---|
| 4 |
|
|---|
| 5 | const isPlainObject = require('../predicate/isPlainObject.js');
|
|---|
| 6 |
|
|---|
| 7 | function defaultsDeep(target, ...sources) {
|
|---|
| 8 | target = Object(target);
|
|---|
| 9 | for (let i = 0; i < sources.length; i++) {
|
|---|
| 10 | const source = sources[i];
|
|---|
| 11 | if (source != null) {
|
|---|
| 12 | defaultsDeepRecursive(target, source, new WeakMap());
|
|---|
| 13 | }
|
|---|
| 14 | }
|
|---|
| 15 | return target;
|
|---|
| 16 | }
|
|---|
| 17 | function defaultsDeepRecursive(target, source, stack) {
|
|---|
| 18 | for (const key in source) {
|
|---|
| 19 | const sourceValue = source[key];
|
|---|
| 20 | const targetValue = target[key];
|
|---|
| 21 | if (targetValue === undefined || !Object.hasOwn(target, key)) {
|
|---|
| 22 | target[key] = handleMissingProperty(sourceValue, stack);
|
|---|
| 23 | continue;
|
|---|
| 24 | }
|
|---|
| 25 | if (stack.get(sourceValue) === targetValue) {
|
|---|
| 26 | continue;
|
|---|
| 27 | }
|
|---|
| 28 | handleExistingProperty(targetValue, sourceValue, stack);
|
|---|
| 29 | }
|
|---|
| 30 | }
|
|---|
| 31 | function handleMissingProperty(sourceValue, stack) {
|
|---|
| 32 | if (stack.has(sourceValue)) {
|
|---|
| 33 | return stack.get(sourceValue);
|
|---|
| 34 | }
|
|---|
| 35 | if (isPlainObject.isPlainObject(sourceValue)) {
|
|---|
| 36 | const newObj = {};
|
|---|
| 37 | stack.set(sourceValue, newObj);
|
|---|
| 38 | defaultsDeepRecursive(newObj, sourceValue, stack);
|
|---|
| 39 | return newObj;
|
|---|
| 40 | }
|
|---|
| 41 | return sourceValue;
|
|---|
| 42 | }
|
|---|
| 43 | function handleExistingProperty(targetValue, sourceValue, stack) {
|
|---|
| 44 | if (isPlainObject.isPlainObject(targetValue) && isPlainObject.isPlainObject(sourceValue)) {
|
|---|
| 45 | stack.set(sourceValue, targetValue);
|
|---|
| 46 | defaultsDeepRecursive(targetValue, sourceValue, stack);
|
|---|
| 47 | return;
|
|---|
| 48 | }
|
|---|
| 49 | if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
|
|---|
| 50 | stack.set(sourceValue, targetValue);
|
|---|
| 51 | mergeArrays(targetValue, sourceValue, stack);
|
|---|
| 52 | }
|
|---|
| 53 | }
|
|---|
| 54 | function mergeArrays(targetArray, sourceArray, stack) {
|
|---|
| 55 | const minLength = Math.min(sourceArray.length, targetArray.length);
|
|---|
| 56 | for (let i = 0; i < minLength; i++) {
|
|---|
| 57 | if (isPlainObject.isPlainObject(targetArray[i]) && isPlainObject.isPlainObject(sourceArray[i])) {
|
|---|
| 58 | defaultsDeepRecursive(targetArray[i], sourceArray[i], stack);
|
|---|
| 59 | }
|
|---|
| 60 | }
|
|---|
| 61 | for (let i = minLength; i < sourceArray.length; i++) {
|
|---|
| 62 | targetArray.push(sourceArray[i]);
|
|---|
| 63 | }
|
|---|
| 64 | }
|
|---|
| 65 |
|
|---|
| 66 | exports.defaultsDeep = defaultsDeep;
|
|---|