Created
June 19, 2019 13:44
-
-
Save jordangarcia/f4f8c61ab8da438eae79261bb527824a 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
// Warm up 6/18/2019 | |
// Week01 Day 3 | |
// Object Equality? | |
// In JS, two different objects are never actually equal | |
// const objA = {a: 7, b: 8} | |
// const objB = {a: 7, b: 8} | |
// objA === objB -> false | |
// objA == objB -> false | |
// that is... unless they reference the same data | |
// var objC = objA | |
// objA === objC -> true | |
// objA == objC -> true | |
// Write a function that takes two objects and returns true if | |
// both objects have the same exact key/value pairs. You can | |
// assume all values are primitive data types (no arrays, objects, etc) | |
const isEquivalentObject = function(objA, objB) { | |
var keys1 = Object.keys(objA).sort(); | |
var keys2 = Object.keys(objB).sort(); | |
if (keys1.length !== keys2.length) { | |
return false; | |
} | |
// ensure key are identical | |
for (let i = 0; i < keys1.length; i++) { | |
if (keys1[i] !== keys2[i]) { | |
return false; | |
} | |
} | |
// sure entries are identical | |
return keys1.every(function(key) { | |
return objA[key] === objB[key]; | |
}); | |
}; | |
// Create 5 test cases on your own. Here are a few to start you off! | |
console.log(isEquivalentObject({ a: 7 }, { a: 7 }) === true); // true | |
console.log(isEquivalentObject({ a: 7 }, { a: 7, b: 8 }) === false); // false | |
console.log(isEquivalentObject({ a: "cat" }, { a: "cat" }) === true); // huh.. should this be true or false?🤔 | |
console.log( | |
isEquivalentObject({ a: "cat", b: "bone" }, { b: "bone", a: "cat" }) === true | |
); | |
console.log(isEquivalentObject({ a: undefined }, { b: undefined }) === false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment