Skip to content

Commit

Permalink
iAPI: Add comments to the deepMerge() function (WordPress#66220)
Browse files Browse the repository at this point in the history
* update comment

* Add comments

Co-authored-by: michalczaplinski <[email protected]>
Co-authored-by: DAreRodz <[email protected]>
  • Loading branch information
3 people authored and karthick-murugan committed Nov 13, 2024
1 parent b45f286 commit b8ea316
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions packages/interactivity/src/proxies/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,8 @@ const deepMergeRecursive = (
source: any,
override: boolean = true
) => {
// If target is not a plain object and the source is, we don't need to merge
// them because the source will be used as the new value of the target.
if ( ! ( isPlainObject( target ) && isPlainObject( source ) ) ) {
return;
}
Expand All @@ -317,38 +319,50 @@ const deepMergeRecursive = (
hasPropSignal( proxy, key ) &&
getPropSignal( proxy, key );

// Handle getters and setters
if (
typeof desc.get === 'function' ||
typeof desc.set === 'function'
) {
if ( override || isNew ) {
// Because we are setting a getter or setter, we need to use
// Object.defineProperty to define the property on the target object.
Object.defineProperty( target, key, {
...desc,
configurable: true,
enumerable: true,
} );
// Update the getter in the property signal if it exists
if ( desc.get && propSignal ) {
propSignal.setGetter( desc.get );
}
}

// Handle nested objects
} else if ( isPlainObject( source[ key ] ) ) {
if ( isNew || ( override && ! isPlainObject( target[ key ] ) ) ) {
// Create a new object if the property is new or needs to be overridden
target[ key ] = {};
if ( propSignal ) {
// Create a new proxified state for the nested object
const ns = getNamespaceFromProxy( proxy );
propSignal.setValue(
proxifyState( ns, target[ key ] as Object )
);
}
}
// Both target and source are plain objects, merge them recursively
if ( isPlainObject( target[ key ] ) ) {
deepMergeRecursive( target[ key ], source[ key ], override );
}

// Handle primitive values and non-plain objects
} else if ( override || isNew ) {
Object.defineProperty( target, key, desc );
if ( propSignal ) {
const { value } = desc;
const ns = getNamespaceFromProxy( proxy );
// Proxify the value if necessary before setting it in the signal
propSignal.setValue(
shouldProxy( value ) ? proxifyState( ns, value ) : value
);
Expand Down

0 comments on commit b8ea316

Please sign in to comment.