Last active
February 14, 2024 16:17
-
-
Save jsjain/a2ba5d40f20e19f734a53c0aad937fbb to your computer and use it in GitHub Desktop.
basic native implementation for isEqual lodash
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
const isEqual = (first: any, second: any): boolean => { | |
if (first === second) { | |
return true; | |
} | |
if ((first === undefined || second === undefined || first === null || second === null) | |
&& (first || second)) { | |
return false; | |
} | |
const firstType = first?.constructor.name; | |
const secondType = second?.constructor.name; | |
if (firstType !== secondType) { | |
return false; | |
} | |
if (firstType === 'Array') { | |
if (first.length !== second.length) { | |
return false; | |
} | |
let equal = true; | |
for (let i = 0; i < first.length; i++) { | |
if (!isEqual(first[i], second[i])) { | |
equal = false; | |
break; | |
} | |
} | |
return equal; | |
} | |
if (firstType === 'Object') { | |
let equal = true; | |
const fKeys = Object.keys(first); | |
const sKeys = Object.keys(second); | |
if (fKeys.length !== sKeys.length) { | |
return false; | |
} | |
for (let i = 0; i < fKeys.length; i++) { | |
if (first[fKeys[i]] && second[fKeys[i]]) { | |
if (first[fKeys[i]] === second[fKeys[i]]) { | |
continue; // eslint-disable-line | |
} | |
if (first[fKeys[i]] && (first[fKeys[i]].constructor.name === 'Array' | |
|| first[fKeys[i]].constructor.name === 'Object')) { | |
equal = isEqual(first[fKeys[i]], second[fKeys[i]]); | |
if (!equal) { | |
break; | |
} | |
} else if (first[fKeys[i]] !== second[fKeys[i]]) { | |
equal = false; | |
break; | |
} | |
} else if ((first[fKeys[i]] && !second[fKeys[i]]) || (!first[fKeys[i]] && second[fKeys[i]])) { | |
equal = false; | |
break; | |
} | |
} | |
return equal; | |
} | |
return first === second; | |
}; |
There is a syntax error in the first line:
function isEqual = (first, second) => {
It should be:
var isEqual = (first, second) => {
or
function isEqual(first, second) {
Thanks @euglv, for pointing it out I missed it while pasting it in the gist. Fixed it now.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sorry, i forgot this nested case, have updated the gist, should work fine now.