preloader
軟體工程

Frontend coding test: Implement Simplified-Version Function Like Lodash Get | 前端測驗題: 實做 lodash get 函式簡易版

Frontend coding test: Implement Simplified-Version Function Like Lodash Get | 前端測驗題: 實做 lodash get 函式簡易版

大廠面試前端工程師時,偶爾會考前端函式庫某一函式的手寫白板題,lodash 函式庫的 get() 是題目之一,會請面試者現場做出簡易版的函式,本文提供解答的程式碼。

以下是我寫在 github 的改良方法@github,感謝同討論串的前人 jsspace 提供方法框架,讓我能在它的基礎上改進。

/**
 * 從 github 找到的內容,大致是對的,https://github.com/metroluffy/fe-learning/issues/16#issuecomment-810816445
 * 我改良後是完全正確, https://github.com/metroluffy/fe-learning/issues/16#issuecomment-2571525937 
 */ 
function get (source, path, defaultValue = undefined) {
  // translate array case to dot case, then split witth .
  // a[0].b -> a.0.b -> ['a', '0', 'b']
  // a[0]["b"]["c"] -> a.0."b"."c" -> ['a', '0', '"b"', '"c"']
  const keyList = path.replace(/\[((\d+)|\"[a-zA-Z]+\")\]/g, '.$1').split('.')
 
  const result = keyList.reduce((obj, key) => {
      if (key.includes('"')) {
        const refinedKey = key.replace(/\"/g, '') // remove all double-quote characters within a key, so '"b"' -> 'b'
        return Object(obj)[refinedKey]
      }
      return Object(obj)[key]; // null undefined get attribute will throwError, Object() can return a object 
  }, source)
  return result === undefined ? defaultValue : result;
}
const object = { a: [{ b: { c: 3 } }] };

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

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

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

這能解決 explainthis 網站中文版英文版 的題目: 實作 lodash get() 題目, explainthis網站不小心提供的錯誤解決方法。


  以下是錯誤解決方法的截圖:

explainthis中文版lodash get()錯誤的解決方法
explainthis英文版lodash get()錯誤的解決方法