This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
85. implement `_.get()`
Here's one possible implementation of a get()
function:
function get(obj, path, defaultValue) { const keys = Array.isArray(path) ? path : path.split('.'); let value = obj; for (let key of keys) { if (value && typeof value === 'object') { value = Array.isArray(value) ? value[parseInt(key)] : value[key]; } else { value = undefined; break; } } return value === undefined ? defaultValue : value;}
This implementation first checks if the path
is given as an array or a string. Then it splits the path
into individual keys and loops over them, checking if each key is a valid property of the value
object. If it is, the value
is updated to the corresponding property value. If it's not, the loop is broken and undefined
is returned.
At the end, the function returns either the value
if it's not undefined
, or the defaultValue
if it's provided.
This implementation should be able to handle the test cases provided in the prompt.