From 4a86b3ed8e1a91294e6f067329ab6a7c981ec336 Mon Sep 17 00:00:00 2001 From: Igor Kamyshev Date: Mon, 30 Oct 2023 16:28:30 +0700 Subject: [PATCH] Fix undefined case in isEqual with custom classes with no valueOf --- .changeset/eighty-laws-accept.md | 5 ++++ .../libs/lohyphen/__tests__/is_equal.test.ts | 24 +++++++++++++------ packages/core/src/libs/lohyphen/is_equal.ts | 16 +------------ 3 files changed, 23 insertions(+), 22 deletions(-) create mode 100644 .changeset/eighty-laws-accept.md diff --git a/.changeset/eighty-laws-accept.md b/.changeset/eighty-laws-accept.md new file mode 100644 index 000000000..63e087bd9 --- /dev/null +++ b/.changeset/eighty-laws-accept.md @@ -0,0 +1,5 @@ +--- +'@farfetched/core': patch +--- + +Fix undefined case in isEqual with custom classes with no valueOf diff --git a/packages/core/src/libs/lohyphen/__tests__/is_equal.test.ts b/packages/core/src/libs/lohyphen/__tests__/is_equal.test.ts index 2d31ab1b0..5ed74a622 100644 --- a/packages/core/src/libs/lohyphen/__tests__/is_equal.test.ts +++ b/packages/core/src/libs/lohyphen/__tests__/is_equal.test.ts @@ -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); }); }); diff --git a/packages/core/src/libs/lohyphen/is_equal.ts b/packages/core/src/libs/lohyphen/is_equal.ts index d874a1a10..5b7905c94 100644 --- a/packages/core/src/libs/lohyphen/is_equal.ts +++ b/packages/core/src/libs/lohyphen/is_equal.ts @@ -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