From ca51b2c43f7a6b6dc3b17b1d7efe0a5a5493c617 Mon Sep 17 00:00:00 2001 From: AsyncBanana Date: Fri, 5 Nov 2021 17:43:03 -0400 Subject: [PATCH] Added support for more class types like regex --- index.ts | 13 ++++++++----- tests/class-primitives.js | 26 ++++++++++++++++++++++++++ tests/regex.js | 19 +++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) create mode 100644 tests/class-primitives.js create mode 100644 tests/regex.js diff --git a/index.ts b/index.ts index 6ba555e..bbc5ce4 100644 --- a/index.ts +++ b/index.ts @@ -3,7 +3,8 @@ interface Difference { path: string[]; value?: any; } - +const t = true; +const richTypes = { Date: t, RegExp: t, String: t, Number: t }; export default function diff( obj: Record | any[], newObj: Record | any[] @@ -18,7 +19,7 @@ export default function diff( } else if ( obj[key] && typeof obj[key] === "object" && - !(obj[key] instanceof Date) + !richTypes[Object.getPrototypeOf(obj[key]).constructor.name] ) { const nestedDiffs = diff(obj[key], newObj[key]); diffs.push( @@ -30,9 +31,11 @@ export default function diff( } else if ( obj[key] !== newObj[key] && !( - obj[key] instanceof Date && - newObj[key] instanceof Date && - +obj[key] === +newObj[key] + typeof obj[key] === "object" && + typeof newObj[key] === "object" && + (isNaN(obj[key]) + ? obj[key] + "" === newObj[key] + "" + : +obj[key] === +newObj[key]) ) ) { diffs.push({ diff --git a/tests/class-primitives.js b/tests/class-primitives.js new file mode 100644 index 0000000..37fe199 --- /dev/null +++ b/tests/class-primitives.js @@ -0,0 +1,26 @@ +import { test } from "uvu"; +import * as assert from "uvu/assert"; +import diff from "../dist/index.js"; + +test("Handles equal string classes", () => { + assert.equal( + diff({ string: new String("hi") }, { string: new String("hi") }), + [] + ); +}); + +test("Handles equal number classes", () => { + assert.equal(diff({ number: new Number(1) }, { number: new Number(1) }), []); +}); + +test("Handles unequal number classes", () => { + assert.equal(diff({ number: new Number(1) }, { number: new Number(2) }), [ + { + type: "CHANGE", + path: ["number"], + value: 2, + }, + ]); +}); + +test.run(); diff --git a/tests/regex.js b/tests/regex.js new file mode 100644 index 0000000..5940aa2 --- /dev/null +++ b/tests/regex.js @@ -0,0 +1,19 @@ +import { test } from "uvu"; +import * as assert from "uvu/assert"; +import diff from "../dist/index.js"; + +test("Handles equal regex", () => { + assert.equal(diff({ regex: /a/ }, { regex: /a/ }), []); +}); + +test("Handles unequal regex", () => { + assert.equal(diff({ regex: /a/ }, { regex: /b/ }), [ + { + type: "CHANGE", + path: ["regex"], + value: /b/, + }, + ]); +}); + +test.run();