Skip to content

Commit 32e194e

Browse files
committed
fix: avoid array length truncation in mergeWith and add sparse merge test
1 parent 233afca commit 32e194e

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

src/test/mergeWith.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { mergeWith } from '../utils/set';
2+
3+
describe('mergeWith array merge', () => {
4+
it('should keep existing array length when merging sparse updates', () => {
5+
const allValues = { list: ['A', 'B', 'C', 'D'] };
6+
const changedValues = { list: new Array(2) };
7+
changedValues.list[1] = 'BB'; // 仅更新第 2 项,长度为 2
8+
9+
const merged = mergeWith([allValues, changedValues], {
10+
prepareArray: current => [...(current || [])],
11+
});
12+
13+
expect(merged.list).toEqual(['A', 'BB', 'C', 'D']);
14+
expect(merged.list).toHaveLength(4);
15+
});
16+
});

src/utils/set.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,10 @@ export function mergeWith<T extends object>(
110110
clone = set(clone, path, createEmpty(value));
111111
}
112112

113-
keys(value).forEach(key => {
113+
const valueKeys = isArr
114+
? keys(value).filter(key => key !== 'length')
115+
: keys(value);
116+
valueKeys.forEach(key => {
114117
internalMerge([...path, key], loopSet);
115118
});
116119
}

0 commit comments

Comments
 (0)