Skip to content

implement isEquivalent object #58

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

Merged
merged 2 commits into from
Dec 9, 2022
Merged
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
25 changes: 25 additions & 0 deletions src/problems/is-equivalent-object.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// implementation of some property-based equality checking where each property of the object is compared.

function isEquivalentObj(a: { [key: string]: number | string }, b: { [key: string]: number | string }) {
// Arrays of property names.
const aProps = Object.getOwnPropertyNames(a);
const bProps = Object.getOwnPropertyNames(b);

// If their property lengths are different, they're different objects
if (aProps.length != bProps.length) {
return false;
}

for (let i = 0; i < aProps.length; i++) {
let propName = aProps[i];
// If the values of the property are different, not equal
if (a[propName] !== b[propName]) {
return false;
}
}

// If everything matched, correct
return true;
}
// However, this would still work for objects that have only a string or a number as the property.
isEquivalentObj({ hi: 12 }, { hi: 12 }); // Return true.