Skip to content

Commit

Permalink
fix(merge): should work with nullish variables
Browse files Browse the repository at this point in the history
  • Loading branch information
D-Sketon committed Dec 22, 2024
1 parent 83787c8 commit 207cdb8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
22 changes: 22 additions & 0 deletions src/compat/object/mergeWith.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,26 @@ describe('mergeWith', () => {
expect(mergeWith(target, undefined, noop)).toBe(target);
expect(mergeWith(target, 1, noop)).toBe(target);
});

it('should work with nullish variables', () => {
const source = { a: 1 };
expect(mergeWith(null, source, noop)).toEqual(source);
expect(mergeWith(undefined, source, noop)).toEqual(source);
expect(mergeWith(null, undefined, source, noop)).toEqual(source);
expect(mergeWith(null, undefined, noop)).toEqual({});
expect(mergeWith(undefined, null, noop)).toEqual({});
});

it('should merge array to a null prop', () => {
const target = { a: null };
const source = { a: ['abc', '123'] };
expect(mergeWith(target, source, noop)).toEqual({ a: ['abc', '123'] });
});

it('should return an object when the target is a primitive', () => {
expect(mergeWith(1, null, noop)).toEqual(Object(1));
expect(mergeWith('a', null, noop)).toEqual(Object('a'));
expect(mergeWith(true, null, noop)).toEqual(Object(true));
expect(mergeWith(1, { a: 1 }, noop)).toEqual(Object.assign(1, { a: 1 }));
});
});
7 changes: 5 additions & 2 deletions src/compat/object/mergeWith.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { cloneDeep } from './cloneDeep.ts';
import { clone } from '../../object/clone.ts';
import { isPrimitive } from '../../predicate/isPrimitive.ts';
import { getSymbols } from '../_internal/getSymbols.ts';
import { isArguments } from '../predicate/isArguments.ts';
import { isObjectLike } from '../predicate/isObjectLike.ts';
Expand Down Expand Up @@ -360,7 +361,9 @@ export function mergeWith(object: any, ...otherArgs: any[]): any {
source: any,
stack: Map<any, any>
) => any;

if (isPrimitive(object)) {
object = Object(object);
}
let result = object;

for (let i = 0; i < sources.length; i++) {
Expand Down Expand Up @@ -423,7 +426,7 @@ function mergeWithDeep(
}

if (Array.isArray(sourceValue)) {
if (typeof targetValue === 'object') {
if (typeof targetValue === 'object' && targetValue !== null) {
const cloned: any = [];
const targetKeys = Reflect.ownKeys(targetValue);

Expand Down

0 comments on commit 207cdb8

Please sign in to comment.