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