Skip to main content

2628. JSON Deep Equal

https://leetcode.com/problems/json-deep-equal/

Javascript

var areDeeplyEqual = function(o1, o2) {
function dfs(left, right) {
const leftType = typeof left
const rightType = typeof right

// 1. Check type
if (leftType !== rightType) {
return false
}

// 2. Check simple type (bool, number, string, undefined, null, NaN)
if (typeof left !== 'object' || left === null || right === null) {
return left === right
}


// 3. Check Array
if (Array.isArray(left) && Array.isArray(right)) {
if (left.length !== right.length) {
return false
}
for (let i=0; i < left.length; i++) {
if (!dfs(left[i], right[i])) {
return false
}
}
return true
}

if (Array.isArray(left) || Array.isArray(right)) {
return false
}

// 4. Check Object
const leftChildren = Object.keys(left)
const rightChildren = Object.keys(right)

if (leftChildren.length !== rightChildren.length) {
return false
}

for (const key of leftChildren) {
if (!dfs(left[key], right[key])) {
return false
}
}

// 5. Otherwise, they're equal
return true
}

return dfs(o1, o2)
};

Typescript

function areDeeplyEqual(o1: any, o2: any): boolean {
function dfs(left: any, right: any) {
const leftType = typeof left
const rightType = typeof right

// 1. Check type
if (leftType !== rightType) {
return false
}

// 2. Check simple type (bool, number, string, undefined, null, NaN)
if (typeof left !== 'object' || left === null || right === null) {
return left === right
}


// 3. Check Array
if (Array.isArray(left) && Array.isArray(right)) {
if (left.length !== right.length) {
return false
}
for (let i = 0; i < left.length; i++) {
if (!dfs(left[i], right[i])) {
return false
}
}
return true
}

if (Array.isArray(left) || Array.isArray(right)) {
return false
}

// 4. Check Object
const leftChildren = Object.keys(left)
const rightChildren = Object.keys(right)

if (leftChildren.length !== rightChildren.length) {
return false
}

for (const key of leftChildren) {
if (!dfs(left[key], right[key])) {
return false
}
}

// 5. Otherwise, they're equal
return true
}

return dfs(o1, o2)
};