/
πŸ“¬
Shallow Compare & Deep Compare
Search
Try Notion
πŸ“¬πŸ“¬
Shallow Compare & Deep Compare
They are a technic to solve comparison problem that the basic JavaScript Operators can’t solve by itself alone, like comparing if two objects are both equal in data type, size and value. And as you probably have guessed, shallow strategy compares superficially 2 operands equality 1st level in depth only while deep strategy compares the equality from all depth levels.
Shallow
Deep
Fast Performance
βœ…
❌
Order Matter
❌
βœ…
Reference Equality
βœ…
❌
Strict
βœ…
βœ…
Shallow Compare Syntax :
import typeOf from './type-of'; const shallowCompare = (source, target) => { if (typeOf(source) !== typeOf(target)) { return false; } if (typeOf(source) === 'array') { return source.length === target.length; } else if (typeOf(source) === 'object') { return Object.keys(source).every((key) => source[key] === target[key]); } else if (typeOf(source) === 'date') { return source.getTime() === target.getTime(); } return source === target; };
JavaScript
Deep Compare Syntax :
const deepCompare = (source, target) => { if (typeOf(source) !== typeOf(target)) { return false; } if (typeOf(source) === 'array') { if (source.length !== target.length) { return false; } return source.every((entry, index) => deepCompare(entry, target[index])) } else if (typeOf(source) === 'object') { if (Object.keys(source).length !== Object.keys(target).length) { return false; } return Object.keys(source).every((key) => deepCompare(source[key], target[key])); } else if (typeOf(source) === 'date') { return source.getTime() === target.getTime(); } return source === target; };
JavaScript
Summary β†’
we can say that shallow compare is less strict than deep compare as its name also suggest!
The shallow compare doesn’t iterate all the values inside variable or object but deep compare does!
For reference :