Skip to content
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
8 changes: 8 additions & 0 deletions src/object/merge.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,12 @@ describe('merge', () => {
expect(result).toEqual({ a: 2 });
expect(result.__proto__).toBe(Object.prototype);
});

it('should handle top-level type mismatch consistently with nested behavior', () => {
const topLevelResult = merge(['1'] as any, { a: 2 });
const nestedResult = merge({ x: ['1'] }, { x: { a: 2 } } as any);

expect(topLevelResult).toEqual({ a: 2 });
expect(nestedResult.x).toEqual({ a: 2 });
});
});
10 changes: 10 additions & 0 deletions src/object/merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ export function merge<T extends Record<PropertyKey, any>, S extends Record<Prope
target: T,
source: S
): T & S {
if (Array.isArray(source)) {
if (!Array.isArray(target)) {
return merge([] as unknown as T, source);
}
} else if (isPlainObject(source)) {
if (!isPlainObject(target)) {
return merge({} as unknown as T, source);
}
}

const sourceKeys = Object.keys(source) as Array<keyof S>;

for (let i = 0; i < sourceKeys.length; i++) {
Expand Down
8 changes: 8 additions & 0 deletions src/object/mergeWith.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,12 @@ describe('mergeWith', () => {

expect(result).toEqual({ a: { b: { x: 1 }, c: { y: 2 }, d: { z: 3 } } });
});

it('should handle top-level type mismatch consistently with nested behavior', () => {
const topLevelResult = mergeWith(['1'] as any, { a: 2 }, () => undefined);
const nestedResult = mergeWith({ x: ['1'] }, { x: { a: 2 } } as any, () => undefined);

expect(topLevelResult).toEqual({ a: 2 });
expect(nestedResult.x).toEqual({ a: 2 });
});
});
10 changes: 10 additions & 0 deletions src/object/mergeWith.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ export function mergeWith<T extends Record<PropertyKey, any>, S extends Record<P
source: S,
merge: (targetValue: any, sourceValue: any, key: string, target: T, source: S) => any
): T & S {
if (Array.isArray(source)) {
if (!Array.isArray(target)) {
return mergeWith([] as unknown as T, source, merge);
}
} else if (isPlainObject(source)) {
if (!isPlainObject(target)) {
return mergeWith({} as unknown as T, source, merge);
}
}

const sourceKeys = Object.keys(source) as Array<keyof T>;

for (let i = 0; i < sourceKeys.length; i++) {
Expand Down