Skip to content

Commit

Permalink
Merge pull request #32 from EveripediaNetwork/is-deep-equal
Browse files Browse the repository at this point in the history
done adding logic for deep comparison
  • Loading branch information
Aliiiu authored Apr 12, 2024
2 parents 73ab48e + 2516a5c commit 46f00c0
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/is-deeped-equal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@everipedia/iq-utils': patch
---

Create lib for deep comparison
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@everipedia/iq-utils",
"version": "0.2.4",
"version": "0.2.5",
"description": "Common utility library for IQ projects",
"main": "build/main/index.js",
"typings": "build/main/index.d.ts",
Expand Down
52 changes: 52 additions & 0 deletions src/lib/isDeepEqual.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
function isDeepEqual(obj1: any, obj2: any): boolean {
// If both are strings, compare them ignoring whitespace
if (typeof obj1 === 'string' && typeof obj2 === 'string') {
return obj1.replace(/\s+/g, '') === obj2.replace(/\s+/g, '');
}

// Check if they are the same reference or both null/undefined
if (obj1 === obj2) {
return true;
}

// Check if either is null/undefined, or not both are objects (including functions)
if (
typeof obj1 !== 'object' ||
obj1 === null ||
typeof obj2 !== 'object' ||
obj2 === null
) {
return false;
}

// Get the keys of both objects
const keysA = Object.keys(obj1);
const keysB = Object.keys(obj2);

// Check if the number of properties is different
if (keysA.length !== keysB.length) {
return false;
}

// Check if obj2 has all keys present in obj1 and compare each key
for (const key of keysA) {
if (!keysB.includes(key)) {
return false;
}

// Check if the property is a function and compare the function's code
if (typeof obj1[key] === 'function' || typeof obj2[key] === 'function') {
if (obj1[key].toString() !== obj2[key].toString()) {
return false;
}
} else {
// Recursive call for nested objects or arrays
if (!isDeepEqual(obj1[key], obj2[key])) {
return false;
}
}
}
return true;
}

export default isDeepEqual;

0 comments on commit 46f00c0

Please sign in to comment.