This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
69. implement deep equal `_.isEqual()`
One possible implementation of deep equal isEqual
is as follows:
function isEqual(a, b) { // First, check if both inputs are the same reference if (a === b) { return true; } // Check if both inputs are objects or arrays if (typeof a === 'object' && typeof b === 'object' && a !== null && b !== null) { // Get the keys of both inputs const keysA = Object.keys(a); const keysB = Object.keys(b); // Check if the number of keys is the same if (keysA.length !== keysB.length) { return false; } // Check if all keys in A are also in B, and if their values are equal for (const key of keysA) { if (!keysB.includes(key) || !isEqual(a[key], b[key])) { return false; } } // All keys in A are also in B, and their values are equal return true; } // If inputs are not objects or arrays, use strict equality return a === b;}
This implementation recursively checks the equality of objects and arrays, and uses strict equality (===
) for all other types of input. The function returns true
if and only if both inputs are equal by value, not reference.
Note that this implementation will not have the same problem as the lodash implementation with self-referencing objects, since it only checks enumerable properties, not the entire object.