-
Notifications
You must be signed in to change notification settings - Fork 0
/
eqObjects.js
67 lines (58 loc) · 2.17 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const eqArrays = function(array1, array2) {
if (array1.length !== array2.length) {
return false
}
for (let i = 0; i < array1.length; i++) {
if (Array.isArray(array1[i]) && (eqArrays(array1[i], array2[i]) === false)) {
return false;
}
if (!(Array.isArray(array1[i])) && array1[i] !== array2[i]) {
return false;
}
}
return true;
};
const assertEquals = function(actual, expected) {
if (actual === expected) {
console.log(`✅✅✅ Assertion Passed: ${actual} === ${expected}`);
} else {
console.log(`🛑🛑🛑 Assertion Failed: ${actual} !== ${expected}`);
}
};
// Returns true if both objects have identical keys with identical values.
// Otherwise you get back a big fat FALSE!
const eqObjects = function(object1, object2) {
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
for (let key of keys1) {
const val1 = object1[key];
const val2 = object2[key];
if (Array.isArray(val1) && Array.isArray(val2)) {
if (!eqArrays(val1, val2)) {
return false;
}
} else if (typeof val1 === 'object' && typeof val2 === 'object') {
if (!eqObjects(val1, val2)) {
return false;
}
} else if (val1 !== val2) {
return false;
}
}
return true;
};
const shirtObject = { color: "red", size: "medium" };
const anotherShirtObject = { size: "medium", color: "red" };
eqObjects(shirtObject , anotherShirtObject); // => true
assertEquals(eqObjects(shirtObject , anotherShirtObject), true);
const longSleeveShirtObject = { size: "medium", color: "red", sleeveLength: "long" };
eqObjects(shirtObject, longSleeveShirtObject); // => false
assertEquals(eqObjects(shirtObject , longSleeveShirtObject), false);
const multiColorShirtObject = { colors: ["red", "blue"], size: "medium" };
const anotherMultiColorShirtObject = { size: "medium", colors: ["red", "blue"] };
eqObjects(multiColorShirtObject , anotherMultiColorShirtObject); // => true
const longSleeveMultiColorShirtObject = { size: "medium", colors: ["red", "blue"], sleeveLength: "long" };
eqObjects(multiColorShirtObject , longSleeveMultiColorShirtObject); // => false