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

Consider undefined properties equivalent to missing properties. #21

Merged
merged 1 commit into from
Oct 1, 2020
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions packages/equality/src/equality.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ function check(a: any, b: any): boolean {
case '[object Object]': {
if (previouslyCompared(a, b)) return true;

const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
const aKeys = definedKeys(a);
const bKeys = definedKeys(b);

// If `a` and `b` have a different number of enumerable keys, they
// must be different.
Expand Down Expand Up @@ -151,6 +151,18 @@ function check(a: any, b: any): boolean {
return false;
}

function definedKeys<TObject extends object>(obj: TObject) {
// Remember that the second argument to Array.prototype.filter will be
// used as `this` within the callback function.
return Object.keys(obj).filter(isDefinedKey, obj);
}
function isDefinedKey<TObject extends object>(
this: TObject,
key: keyof TObject,
) {
return this[key] !== void 0;
}

const nativeCodeSuffix = "{ [native code] }";

function endsWith(full: string, suffix: string) {
Expand Down
20 changes: 19 additions & 1 deletion packages/equality/src/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,12 @@ describe("equality", function () {
[1, /*hole*/, 3],
);

assertNotEqual(
assertEqual(
[1, /*hole*/, 3],
[1, void 0, 3],
);

// Not equal because the arrays are a different length.
assertNotEqual(
[1, 2, /*hole*/,],
[1, 2],
Expand Down Expand Up @@ -102,6 +103,23 @@ describe("equality", function () {
assertNotEqual(a, b);
});

it("should consider undefined and missing object properties equivalent", function () {
assertEqual({
a: 1,
b: void 0,
c: 3,
}, {
a: 1,
c: 3,
});

assertEqual({
a: void 0,
b: void 0,
c: void 0,
}, {});
});

it("should work for Error objects", function () {
assertEqual(new Error("oyez"), new Error("oyez"));
assertNotEqual(new Error("oyez"), new Error("onoz"));
Expand Down