Last active
June 15, 2019 21:54
-
-
Save Gbahdeyboh/62cd11c67f4a7ce88fafc35a492e5923 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function valueHandler(val1, val2) { | |
switch (typeof val1) { | |
case 'number': | |
if (val1 !== val2) { | |
reject("An Object value of type `number` mismatched"); | |
} | |
break; | |
case 'boolean': | |
if (val1 !== val2) { | |
reject("An Object value of type `boolean` mismatched"); | |
} | |
break; | |
case 'string': | |
if (val1 !== val2) { | |
reject("An Object value of type `string` mismatched"); | |
} | |
break; | |
case 'function': | |
if (val1.call(val1) !== val2.call(val2)) { | |
reject("An Object value of type `function` mismatched") | |
} | |
break; | |
case 'object': | |
/* | |
* An Object could be anything, literally everything in javascript is an Object. | |
* Different kinds of objects are ompared differently. Date Objects can't be compared the | |
* same way Array or Sets or Regular Expressions are compared. Each type of Object are compared | |
* to each other differently as shown below | |
*/ | |
// Every Array is an Object, so we first have to confirm if the Object is an array before proceeding | |
if (Array.isArray(val1) && Array.isArray(val2)) { | |
for (let j in val1) { | |
//loop through the array and handle each data type in the array recursively | |
valueHandler(val1[j], val2[j]); | |
} | |
} | |
//Check if both Objects are instances of a Regular Expresion | |
if (val1 instanceof RegExp || val2 instanceof RegExp) { | |
String(val1) !== String(val2) ? reject("The regular Expressions are different") : true; | |
} | |
//Check if both Objects are instances of a Date Object | |
if (val1 instanceof Date || val2 instanceof Date) { | |
val1.valueOf() === val2.valueOf() ? true : reject("The Date Objects do not match") | |
} | |
//Check if both functions are instanes of a Set Object | |
if (val1 instanceof Set || val2 instanceof Set) { | |
val1.size !== val2.size ? reject("The Set's Objects are of different sizes") : true; | |
for (let a of val1) { | |
if (!val2.has(a)) reject("The Sets values are not equal"); | |
} | |
} | |
//If it's a regular object, call the parent function (compareObjects) recursively | |
compareObjects(val1, val2); | |
break; | |
default: | |
reject("An Object value type that isn't supported was passed in"); | |
} | |
} | |
valueHandler(value1, value2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment