69. implement deep equal `_.isEqual()`
Share
medium - accepted / - tried
_.isEqual is useful when you want to compare complex data types by value not the reference.
Can you implement your own version of deep equal isEqual
? The lodash version covers a lot of data types. In this problem, you are asked to support :
- primitives
- plain objects (object literals)
- array
Objects are compared by their own, not inherited, enumerable properties
const a = {a: 'bfe'}const b = {a: 'bfe'}isEqual(a, b) // truea === b // falseconst c = [1, a, '4']const d = [1, b, '4']isEqual(c, d) // truec === d // false
Lodash implementation has some strange behaviors. (github issue, like following code
const a = {}a.self = aconst b = {self: a}const c = {}c.self = cconst d = {self: {self: a}}const e = {self: {self: b}}
lodash.isEqual
gives us following result. Notice there is a case that resulting in false
.
// result from lodash implementation_.isEqual(a, b) // true_.isEqual(a, c) // true_.isEqual(a, d) // true_.isEqual(a, e) // true_.isEqual(b, c) // true_.isEqual(b, d) // true_.isEqual(b, e) // false_.isEqual(c, d) // true_.isEqual(c, e) // true_.isEqual(d, e) // true
Setting aside the performance concerns mentioned by lodash, your implement should not have above problem, which means above all returns true and call stack should not exceed the maximum.