Last active
August 11, 2020 18:47
-
-
Save arpanpreneur/8e5380edd444a77daa2fd3dabc8ec819 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
// Best Case is O(1) worst case in O(n) | |
// where n is the no of nodes in the tree represented by the object | |
function deepCheck(obj1, obj2) { | |
// If they are equal Primitives (think as leaf nodes) or they refer to same memory | |
if (obj1 === obj2) return true; | |
// If Both are NaN | |
if (obj1 === NaN && obj2 === NaN) return true; | |
// They aren't equal primitives and also same memory | |
// But one of them is null | |
if (obj1 === null || obj2 === null) return false; | |
// If they are of different types | |
if (typeof(obj1) !== typeof(obj2)) return false; | |
// So both are objects and we need to see if they have equal no. of keys | |
if (typeof(obj1) === 'object' && Object.keys(obj1).length === Object.keys(obj2).length) { | |
// Recursively Check for each key in Depth First Manner | |
for (let key in obj1) { | |
if (!deepCheck(obj1[key], obj2[key])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
return false; | |
} | |
/* | |
===================================================================================== | |
Now imagine if we have a very nested State Object in our store | |
and we are trying to deepCheck objects for changes, do you think | |
our application will work smoothly? | |
Imagine this way, you have a text field, which on changing | |
this deepCheck function is called. This is done on every keystroke. | |
Or maybe on the mousemove event, every time you move your | |
mouse pointer.... | |
For what? Just to know if anything has changed? Better never modify | |
and return new reference of State object. So that a simple shallow check | |
like obj1 === obj2 is sufficient. | |
And that's where you land State Immutability. | |
===================================================================================== | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Amazing explanation!