AI solution for JavaScript Coding Question on BFE.dev
156. implement `_.set()`
One possible implementation of set()
in JavaScript is:
function set(obj, path, value) { if (!Array.isArray(path)) { path = path.replace(/\[(\w+)\]/g, '.$1').split('.') } path.reduce((acc, key, index) => { if (index === path.length - 1) { acc[key] = value } else if (index === 0) { if (key in obj) { return obj[key] } else { obj[key] = isNaN(parseInt(path[index + 1])) ? {} : [] return obj[key] } } else { if (key in acc) { return acc[key] } else { acc[key] = isNaN(parseInt(path[index + 1])) ? {} : [] return acc[key] } } }, obj)}
The set()
function takes three arguments:
obj
: the object to modify.path
: a string or an array of keys that indicate the property path to modify.value
: the new value to set.
The function first checks whether path
is an array or a string, and converts it into an array of keys if it's a string, handling both dot and bracket notation. It then iterates over those keys, checking whether the current key exists in the current accumulator (obj
or the previous nested object/array) or not.
If it's the last key in the path, then the function sets the value
of that key. If it's the first key, then the function checks whether it's already in the root obj
, otherwise it creates a new object or array based on whether the next key is a string or numeric. If it's not the first key, then the function checks whether the key exists in the current accumulator or not, similarly creating a new object or array if it's not.
This implementation supports all the test cases in the prompt, including both numeric and string-based property accessors, as well as the automatic conversion of invalid numeric property strings back to regular string property names. Note that the implementation is not the most efficient, as it has to traverse the entire path array on each call, so it may not be suitable for performance-critical scenarios.