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 bugs that occur in the presence of Array polyfills #10328

Merged
merged 1 commit into from
Apr 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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