Skip to content

Commit

Permalink
Added support for more class types like regex
Browse files Browse the repository at this point in the history
  • Loading branch information
AsyncBanana committed Nov 5, 2021
1 parent de62aca commit ca51b2c
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 5 deletions.
13 changes: 8 additions & 5 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, any> | any[],
newObj: Record<string, any> | any[]
Expand All @@ -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(
Expand All @@ -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({
Expand Down
26 changes: 26 additions & 0 deletions tests/class-primitives.js
Original file line number Diff line number Diff line change
@@ -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();
19 changes: 19 additions & 0 deletions tests/regex.js
Original file line number Diff line number Diff line change
@@ -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();

0 comments on commit ca51b2c

Please sign in to comment.