Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(merge): Handle edge-case for merge #556

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/object/merge.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,37 @@ describe('merge', () => {
expect(result).toEqual({ a: [1, 2, 3] });
});

it('should handle merging arrays into non-array target values', () => {
const target = { a: 1, b: {} };
const numbers = [1, 2, 3];
const source = { b: numbers, c: 4 };
const result = merge(target, source);

expect(result).toEqual({ a: 1, b: numbers, c: 4 });
expect(result.b).not.toBe(numbers);
});

it('should create new plain object when merged', () => {
const plainObject = { b: 2 } as const;
const target = {};
const source = { a: plainObject };
const result = merge(target, source);

expect(result).toEqual({ a: plainObject });
expect(result.a).not.toBe(plainObject);
});

it('should handle merging values that are neither arrays nor plain objects', () => {
const date = new Date();
const target = {};
const source = { a: date };
const result = merge(target, source);

expect(result).toEqual({ a: date });
// unlike arrays and plain objects, the original value is used.
expect(result.a).toBe(date);
});

it('should not overwrite existing values with undefined from source', () => {
const target = { a: 1, b: 2 };
const source = { b: undefined, c: 3 };
Expand Down
8 changes: 4 additions & 4 deletions src/object/merge.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isObjectLike } from '../compat/predicate/isObjectLike.ts';
import { isPlainObject } from '../predicate/isPlainObject.ts';

/**
* Merges the properties of the source object into the target object.
Expand Down Expand Up @@ -91,9 +91,9 @@ export function merge(target: any, source: any) {
const targetValue = target[key];

if (Array.isArray(sourceValue)) {
target[key] = merge(targetValue ?? [], sourceValue);
} else if (isObjectLike(targetValue) && isObjectLike(sourceValue)) {
target[key] = merge(targetValue ?? {}, sourceValue);
target[key] = merge(Array.isArray(targetValue) ? targetValue : [], sourceValue);
} else if (isPlainObject(sourceValue)) {
target[key] = merge(isPlainObject(targetValue) ? targetValue : {}, sourceValue);
} else if (targetValue === undefined || sourceValue !== undefined) {
target[key] = sourceValue;
}
Expand Down