Deep Equal For Nested Objects

Compare nested objects for deep equality handling arrays dates maps and circular references without stack overflow.

JavascriptData Integrity

Code

javascriptsnippet
1 line
export function deepEqual(a,b,seen=new WeakSet()){if(a===b)return true;if(a===null||b===null||typeof a!=='object'||typeof b!=='object')return false;if(seen.has(a)||seen.has(b))return a===b;seen.add(a);seen.add(b);if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return false;return a.every((v,i)=>deepEqual(v,b[i],seen));}if(a instanceof Map&&b instanceof Map){if(a.size!==b.size)return false;for(const[k,v]of a)if(!b.has(k)||!deepEqual(v,b.get(k),seen))return false;return true;}const ak=Object.keys(a),bk=Object.keys(b);if(ak.length!==bk.length)return false;return ak.every(k=>deepEqual(a[k],b[k],seen));}

How it works

Deep Equal For Nested Objects keeps everything in the function deepEqual.

Watch out for

  • The guard a===b short-circuits the flow with an early return when its condition holds.

Taking the usage further

Signature: export function deepEqual(a,b,seen=new WeakSet()

Import deepEqual from the file and call it — the rest of the code is implementation detail.

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `deepEqual` at load time.