[Medium] 請實現 Lodash 的 .get()

2024年1月26日

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

題目描述

實作一個 get  效用函式。它接收三個參數

  • 一個物件
  • 某個路徑
  • 預設值

而此函式最後會返回路徑的值;如果該路徑不存在於給定的物件,則返回預設值。透過例子會比較好理解:

// 範例
const object = { a: [{ b: { c: 3 } }] };

//=> 3
get(object, "a[0].b.c");

//=> 3
get(object, 'a[0]["b"]["c"]');

//=> 'default'
get(object, "a[100].b.c", "default");

本題解答

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

function get(object, pathParam, defaultValue) {
  if (object == null) {
    return defaultValue;
  }

  let count = 0;

  const path = Array.isArray(pathParam) ? pathParam : pathParam.split(".");
  const length = path.length;

  while (object != null && count < length) {
    object = object[String(path[count])];
    count += 1;
  }

  const result = count && count === length ? object : undefined;

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