/
assertObjectsEqual.js
80 lines (70 loc) · 2.33 KB
/
assertObjectsEqual.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const assertEqual = function (actual, expected) {
if (actual === expected) {
console.log(`Assertion Passed✅: ${actual} === ${expected}.`);
} else {
console.log(`Assertion Failed🚫: ${actual} !== ${expected}.`);
}
};
/* The function eqObjects will take in two objects and returns
true or false, based on a perfect match.
If both objects have identical keys with identical values, returns true.
Otherwise it should return false.
*/
const eqObjects = function (object1, object2) {
if (Object.keys(object1).length !== Object.keys(object2).length) {
return false;
}
for (const key in object1) {
if (!object2.hasOwnProperty(key)) {
return false;
} else if (!Array.isArray(object2[key])) {
if (object1[key] !== object2[key]) {
return false;
}
} else if (Array.isArray(object1[key])) {
for (const e of object1[key]) {
if (!object2[key].includes(e)) {
return false;
}
}
}
}
return true;
};
// Function Implementation
const assertObjectsEqual = function (actual, expected) {
const inspect = require("util").inspect;
if (eqObjects(actual, expected)) {
console.log(
`Assertion Passed✅: ${inspect(actual)} === ${inspect(expected)}.`
);
} else {
console.log(
`Assertion Failed🚫: ${inspect(actual)} !== ${inspect(expected)}.`
);
}
};
const shirtObject = { color: "red", size: "medium" };
const anotherShirtObject = { size: "medium", color: "red" };
console.log(eqObjects(shirtObject, anotherShirtObject)); // => true
const longSleeveShirtObject = {
size: "medium",
color: "red",
sleeveLength: "long",
};
console.log(eqObjects(shirtObject, longSleeveShirtObject)); // => false
const multiColorShirtObject = { colors: ["red", "blue"], size: "medium" };
const anotherMultiColorShirtObject = {
size: "medium",
colors: ["red", "blue"],
};
console.log(eqObjects(multiColorShirtObject, anotherMultiColorShirtObject)); // => true
const longSleeveMultiColorShirtObject = {
size: "medium",
colors: ["red", "blue"],
sleeveLength: "long",
};
console.log(eqObjects(multiColorShirtObject, longSleeveMultiColorShirtObject)); // => false
assertObjectsEqual(shirtObject, anotherShirtObject);
assertObjectsEqual(multiColorShirtObject, anotherMultiColorShirtObject);
assertObjectsEqual(multiColorShirtObject, longSleeveMultiColorShirtObject);