Build a Memoized Deep Object Comparator Function
Create an advanced JavaScript function that deeply compares two objects for structural and value equality, with memoization to optimize repeated comparisons of the same pairs.
Challenge prompt
Write a function named deepCompareMemo that takes two arguments (objA and objB) and returns true if they are deeply equal, or false otherwise. The comparison should handle nested objects, arrays, and primitive values. To optimize, implement memoization so that if the same pair of objects is compared multiple times, the function returns the cached result instead of recomputing. The memoization should uniquely identify pairs regardless of argument order, i.e., deepCompareMemo(objA, objB) and deepCompareMemo(objB, objA) should return the cached value for the same comparison.
Guidance
- • Consider using a WeakMap or Map to store cached comparison results for object pairs.
- • Think about edge cases such as functions, null, and different data types while comparing deeply.
- • Design the memoization key so that the order of arguments does not affect cache hits.
Hints
- • Primitive values can be compared directly with ===, but objects and arrays require recursion.
- • To create a unique key for memoization, consider using pairs of objects stored as nested Maps instead of stringifying.
- • Be careful with circular references; although not required, ensure your function doesn’t crash with them.
Starter code
function deepCompareMemo(objA, objB) {
const cache = new Map();
function isEqual(a, b) {
// Implement deep comparison logic here
}
return isEqual(objA, objB);
}Expected output
deepCompareMemo({a:1, b:[2,3]}, {a:1, b:[2,3]}) // true deepCompareMemo({a:1}, {a:'1'}) // false deepCompareMemo(obj1, obj2) called multiple times returns cached result quickly
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.