Skip to content

Instantly share code, notes, and snippets.

@jsjain
Last active Sep 22, 2021
Embed
What would you like to do?
basic native implementation for isEqual lodash
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;
};
@devlargs
Copy link

devlargs commented May 17, 2020

Tried to copy this code but

image

@jsjain
Copy link
Author

jsjain commented May 18, 2020

sorry, i forgot this nested case, have updated the gist, should work fine now.

@euglv
Copy link

euglv commented Jul 11, 2021

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) {

@jsjain
Copy link
Author

jsjain commented Jul 11, 2021

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