Write a Value by Path

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write set(obj, path, value), the partner of a safe get. path is either a string with dots between keys and array indexes in square brackets, such as cart.items[0].name, or an array of keys, used as they are. Walk the path from obj and put value at the end, creating whatever is missing on the way. When a step is missing, or holds something that isn't an object (a number, a string, null), replace it with a new array if the key after it is a whole number (digits only, like 0 or 12) and with a new plain object otherwise. Keep everything that's already there. set changes obj in place and returns obj.

Your code must pass

  • Sets a nested value on existing objects
  • Creates missing objects along the path
  • Creates arrays for whole-number keys
  • Accepts the path as an array of keys
  • Changes the object in place and returns it