Skip to content

Commit 8b89520

Browse files
Merge pull request #58 from wakidurrahman/feat/is-equivalent-object.ts
implement isEquivalent object
2 parents fd8b609 + 556762b commit 8b89520

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/problems/is-equivalent-object.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// implementation of some property-based equality checking where each property of the object is compared.
2+
3+
function isEquivalentObj(a: { [key: string]: number | string }, b: { [key: string]: number | string }) {
4+
// Arrays of property names.
5+
const aProps = Object.getOwnPropertyNames(a);
6+
const bProps = Object.getOwnPropertyNames(b);
7+
8+
// If their property lengths are different, they're different objects
9+
if (aProps.length != bProps.length) {
10+
return false;
11+
}
12+
13+
for (let i = 0; i < aProps.length; i++) {
14+
let propName = aProps[i];
15+
// If the values of the property are different, not equal
16+
if (a[propName] !== b[propName]) {
17+
return false;
18+
}
19+
}
20+
21+
// If everything matched, correct
22+
return true;
23+
}
24+
// However, this would still work for objects that have only a string or a number as the property.
25+
isEquivalentObj({ hi: 12 }, { hi: 12 }); // Return true.

0 commit comments

Comments
 (0)