Skip to content

Commit 86b6c1c

Browse files
committed
compare object based on Halim's homework
1 parent c11ebca commit 86b6c1c

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Week4/equal.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
'use strict';
2+
3+
const obj1 = {
4+
a: '1',
5+
b: 'this is the letter b',
6+
f: {
7+
foo: 'what is a foo anyway',
8+
bar: [1, 5, '3', 4]
9+
}
10+
};
11+
12+
const obj2 = {
13+
a: 1,
14+
b: 'this is the letter b',
15+
f: {
16+
foo: 'what is a foo anyway',
17+
bar: [1, 5, 3, 4]
18+
}
19+
};
20+
21+
function equal(a, b, mode) {
22+
const eq = mode === 'strict' ? a === b : a == b;
23+
if (eq) {
24+
return true;
25+
}
26+
27+
if (a && b &&
28+
typeof a == 'object' &&
29+
typeof b == 'object' &&
30+
Object.keys(a).length == Object.keys(b).length) {
31+
32+
const keys = Object.keys(a);
33+
for (const key of keys) {
34+
if (b.hasOwnProperty(key)) {
35+
const aValue = a[key];
36+
const bValue = b[key];
37+
if (!equal(aValue, bValue, mode)) {
38+
return false;
39+
}
40+
} else {
41+
return false;
42+
}
43+
}
44+
45+
return true;
46+
}
47+
return false;
48+
};
49+
50+
console.log('objects are equal: ' + equal(obj1, obj2));
51+
console.log('objects are strictly equal: ' + equal(obj1, obj2, 'strict'));

0 commit comments

Comments
 (0)