Skip to content

Commit 98b9267

Browse files
authored
Update README.md
1 parent 4287531 commit 98b9267

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

README.md

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -595,12 +595,31 @@ if(a === b) return true
595595
596596
Then comes the interesting part! There are several data types we need to look out for: Objects, Arrays(which JS treats as an object), and Dates(which is also treated as an object!), thus all we have to do is check if both a and is type object. If not, we can just return false as they didn't pass the ```a === b``` test.
597597
598-
Next, we can process the dates first, as that doesn't require iteration. Make sure to compare ```Date.valueOf()``` instead.
598+
```if(typeof a === "object" && typeof b === "object")...```
599+
600+
Next, we can process the dates first, as that doesn't require iteration. Make sure to compare ```Date.valueOf()``` instead of the date itself.
601+
602+
```if(a instanceof Date && b instanceof Date) return a.valueOf() === b.valueOf()```
599603
600604
Lastly, by taking the keys of the iterables we can compare the length of ```a``` and ```b```, then make use of built-in Array.some method to check if any values of the two iterables don't match.
601605
606+
```const keysA = Object.keys(a) //get keys/index of object/array
607+
if(keysA.length !== Object.keys(b).length) return false //make sure a and b are same length
608+
609+
//Array.some stops executing nested code the moment there is one different value
610+
return !keysA.some( key => {
611+
return !deepCompare(a[key], b[key]) //run deepCompare recursively
612+
})
613+
```
614+
615+
616+
Put it all together, and we have
617+
602618
```js
603-
if(typeof a === "object" && typeof b === "object")
619+
const deepCompare = (a, b) => {
620+
if(a === b) return true
621+
622+
if(typeof a === "object" && typeof b === "object")
604623
{
605624
if(a instanceof Date && b instanceof Date) return a.valueOf() === b.valueOf()
606625
else
@@ -613,9 +632,15 @@ if(typeof a === "object" && typeof b === "object")
613632
}
614633
}
615634
else return false
635+
}
636+
637+
deepCompare(1, 2) //false
638+
const arr = [1, 2, "3", [{4: "5", 6: 7}, 8.0, new Date(), undefined]]
639+
deepCompare(arr, [1, 2, "3", [{4: "5", 6: 7}, 8.0, new Date(), undefined]]) //true
640+
616641
```
617642
618-
It's that simple! Hope this helps.
643+
It's that simple! Hope this helps.
619644
</p>
620645
<hr>
621646
<hr>

0 commit comments

Comments
 (0)