Fix deepClone edge case
This commit is contained in:
@ -12,7 +12,7 @@ const deepClone = obj => {
|
|||||||
Object.keys(clone).forEach(
|
Object.keys(clone).forEach(
|
||||||
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
|
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
|
||||||
);
|
);
|
||||||
return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;
|
return Array.isArray(obj) ? Array.from({ length: obj.length }) : clone;
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@ -8,6 +8,8 @@ const a = { foo: 'bar', obj: { a: 1, b: 2 } };
|
|||||||
const b = deepClone(a);
|
const b = deepClone(a);
|
||||||
const c = [{ foo: 'bar' }];
|
const c = [{ foo: 'bar' }];
|
||||||
const d = deepClone(c);
|
const d = deepClone(c);
|
||||||
|
const e = { edge: [] };
|
||||||
|
const f = deepClone(e);
|
||||||
test('Shallow cloning works', () => {
|
test('Shallow cloning works', () => {
|
||||||
expect(a).not.toBe(b);
|
expect(a).not.toBe(b);
|
||||||
});
|
});
|
||||||
@ -20,3 +22,6 @@ test('Array shallow cloning works', () => {
|
|||||||
test('Array deep cloning works', () => {
|
test('Array deep cloning works', () => {
|
||||||
expect(c[0]).not.toBe(d[0]);
|
expect(c[0]).not.toBe(d[0]);
|
||||||
});
|
});
|
||||||
|
test('Array shallow cloning edge case works', () => {
|
||||||
|
expect(f.edge).toEqual([]);
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user