-
Notifications
You must be signed in to change notification settings - Fork 0
/
eqObjects.js
43 lines (38 loc) · 1.19 KB
/
eqObjects.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const assertEqual = (actual, expected) => {
if (actual === expected) {
console.log(`Assertion Passed: [${actual}] === [${expected}]`);
} else {
console.log(`Assertion Failed: [${actual}] !== [${expected}]`);
}
};
const eqArrays = (arrayA, arrayB) => {
if (arrayA.length !== arrayB.length) {
return false;
}
for (const item of arrayB) {
if (!arrayA.includes(item)) {
return false;
}
}
return true;
};
const eqObjects = function(objectA, objectB) {
if (Object.keys(objectA).length !== Object.keys(objectB).length) {
return false;
}
for (let key in objectA) {
// case where the value is an array
if (Array.isArray(objectA[key])) {
if (!eqArrays(objectA[key], objectB[key]))
return false;
} else if (typeof objectA[key] === "object") { // check if the value is another object
return eqObjects(objectA[key], objectB[key]); // call eqObjects recursively
} else if (objectA[key] !== objectB[key]) return false;
}
return true;
};
const ab = { a: "1", b: "2" };
const ba = { b: "2", a: "1" };
assertEqual(eqObjects(ab, ba), true); // => true
const abc = { a: "1", b: "2", c: "3" };
assertEqual(eqObjects(ab, abc),false); // => false