Skip to content

Commit

Permalink
🐞 fix #9037 bugs that occur in the presence of Array polyfills (#10328)
Browse files Browse the repository at this point in the history
Co-authored-by: Vic Winberry <vic.winberry@xero.com>
  • Loading branch information
Torvin and Vic Winberry committed Apr 24, 2023
1 parent 3a150c2 commit d68ef91
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 3 deletions.
19 changes: 19 additions & 0 deletions src/__tests__/utils/cloneObject.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,23 @@ describe('clone', () => {
other: 'string',
});
});

describe('in presence of Array polyfills', () => {
beforeAll(() => {
// @ts-expect-error
Array.prototype.somePolyfill = () => 123;
});

it('should skip polyfills while cloning', () => {
const data = [1];
const copy = cloneObject(data);

expect(Object.hasOwn(copy, 'somePolyfill')).toBe(false);
});

afterAll(() => {
// @ts-expect-error
delete Array.prototype.somePolyfill;
});
});
});
21 changes: 21 additions & 0 deletions src/__tests__/utils/unset.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,4 +311,25 @@ describe('unset', () => {
expect(test.test.root).toBeDefined();
});
});

describe('in presence of Array polyfills', () => {
beforeAll(() => {
// @ts-expect-error
Array.prototype.somePolyfill = () => 123;
});

it('should delete empty arrays', () => {
const data = {
prop: [],
};
unset(data, 'prop.0');

expect(data.prop).toBeUndefined();
});

afterAll(() => {
// @ts-expect-error
delete Array.prototype.somePolyfill;
});
});
});
6 changes: 4 additions & 2 deletions src/utils/cloneObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ export default function cloneObject<T>(data: T): T {
) {
copy = isArray ? [] : {};

if (!Array.isArray(data) && !isPlainObject(data)) {
if (!isArray && !isPlainObject(data)) {
copy = data;
} else {
for (const key in data) {
copy[key] = cloneObject(data[key]);
if (Object.hasOwn(data, key)) {
copy[key] = cloneObject(data[key]);
}
}
}
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/unset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function baseGet(object: any, updatePath: (string | number)[]) {

function isEmptyArray(obj: unknown[]) {
for (const key in obj) {
if (!isUndefined(obj[key])) {
if (Object.hasOwn(obj, key) && !isUndefined(obj[key])) {
return false;
}
}
Expand Down

0 comments on commit d68ef91

Please sign in to comment.