Skip to content

Commit

Permalink
Fix undefined case in isEqual with custom classes with no valueOf
Browse files Browse the repository at this point in the history
  • Loading branch information
igorkamyshev committed Oct 30, 2023
1 parent d5a3f36 commit 4a86b3e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 22 deletions.
5 changes: 5 additions & 0 deletions .changeset/eighty-laws-accept.md
@@ -0,0 +1,5 @@
---
'@farfetched/core': patch
---

Fix undefined case in isEqual with custom classes with no valueOf
24 changes: 17 additions & 7 deletions packages/core/src/libs/lohyphen/__tests__/is_equal.test.ts
Expand Up @@ -114,19 +114,29 @@ describe('isEqual', () => {
});

describe('Custom objects', () => {
class MyValueObject {
constructor(private value: number) {}
valueOf() {
return this.value;
test('custom object with custom valueOf', () => {
class MyValueObject {
constructor(private value: number) {}
valueOf() {
return this.value;
}
}
}

test('same', () => {
expect(isEqual(new MyValueObject(1), new MyValueObject(1))).toBe(true);
expect(isEqual(new MyValueObject(1), new MyValueObject(2))).toBe(false);
});

test('different', () => {
test('custom object with no custom valueOf', () => {
class MyValueObject {
constructor(public value: number) {}
}

expect(isEqual(new MyValueObject(1), new MyValueObject(2))).toBe(false);
/*
* Consider same obejects as different,
* because we have no idea how to compare them without custom valueOf
*/
expect(isEqual(new MyValueObject(1), new MyValueObject(1))).toBe(false);
});
});

Expand Down
16 changes: 1 addition & 15 deletions packages/core/src/libs/lohyphen/is_equal.ts
Expand Up @@ -71,23 +71,9 @@ export function isEqual(a: any, b: any): boolean {

return true;
} else if (typeA === 'object') {
if (
a.valueOf &&
b.valueOf &&
a.valueOf !== Object.prototype.valueOf() &&
b.valueOf !== Object.prototype.valueOf()
) {
if (a.valueOf && b.valueOf) {
return a.valueOf() === b.valueOf();
}

if (
a.toString &&
a.toString &&
a.toString !== Object.prototype.toString() &&
b.toString !== Object.prototype.toString()
) {
return a.toString() === b.toString();
}
}
} catch (e) {
// We got extremely weird objects, let us skip it and consider them not equal
Expand Down

0 comments on commit 4a86b3e

Please sign in to comment.