[Medium] 手寫 isEqual(深比較)

2024年3月8日

💎 加入 E+ 成長計畫 與超過 300+ 位軟體工程師一同在社群中成長,並且獲得更多的軟體工程學習資源

題目描述

請實作一個 isEqual 函式,此函式會執行深比較。深比較是用來比較兩個不同的物件是否有相同的值。

const object = { a: 1, b: [2, 3] };
const other = { a: 1, b: [2, 3] };

isEqual(object, other);
// => true

本題解答

以下是本題的解答,詳細解題思路可以在 E+ 成長計畫看到

解法

function isEqual(value, other) {
  if (typeof value !== "object" && typeof other !== "object") {
    const isValueNaN = Number.isNaN(value);
    const isOtherNaN = Number.isNaN(other);

    if (isValueNaN && isOtherNaN) {
      return true;
    }

    return value === other;
  }

  if (value === null && other === null) {
    return true;
  }

  if (typeof value !== typeof other) {
    return false;
  }

  if (value === other) {
    return true;
  }

  if (Array.isArray(value) && Array.isArray(other)) {
    if (value.length !== other.length) {
      return false;
    }

    for (let i = 0; i < value.length; i++) {
      if (!isEqual(value[i], other[i])) {
        return false;
      }
    }

    return true;
  }

  if (Array.isArray(value) || Array.isArray(other)) {
    return false;
  }

  if (Object.keys(value).length !== Object.keys(other).length) {
    return false;
  }

  for (const [k, v] of Object.entries(value)) {
    if (!(k in other)) {
      return false;
    }

    if (!isEqual(v, other[k])) {
      return false;
    }
  }

  return true;
}
🧵 如果你想收到最即時的內容更新,可以在 FacebookInstagram 上追蹤我們