Skip to content

Instantly share code, notes, and snippets.

@arpanpreneur
Last active August 11, 2020 18:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arpanpreneur/8e5380edd444a77daa2fd3dabc8ec819 to your computer and use it in GitHub Desktop.
Save arpanpreneur/8e5380edd444a77daa2fd3dabc8ec819 to your computer and use it in GitHub Desktop.
// 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.
=====================================================================================
*/
@divyanshbhowmick
Copy link

Amazing explanation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment