2

During an interview I've got interesting javascript-task:

Given the code:

const testStr = "bar.baz.foo:111222",
      testObj = {
        bar: {
          baz: {
            foo: 333444,
            foo2: 674654
          },
          boo: {
            faa: 11
          }
        },
        fee: 333
      };

function replaceInObj(obj, str) {
  // your code
}

write the implementation of the replaceInObj function

  1. I was not allowed to use 3rd-party library.
  2. I kinda solved the task, but I'm not satisfied with my solution.
  3. And I'm struggling with my complex implementation.
  4. At the same time I cannot find another solution by myself.

My implementation of the replaceInObj function

const testStr = 'bar.baz.foo:111222';
const testObj = {
  bar: {
    baz: {
      foo: 333444,
      foo2: 674654,
    },
    boo: {
      faa: 11,
    },
  },
  fee: 333,
};

console.log('[before] testObj.bar.baz =', testObj.bar.baz);

// run
replaceInObj(testObj, testStr);

console.log('[after] testObj.bar.baz =', testObj.bar.baz);

function replaceInObj(obj, str) {
  const [path, valueToChange] = str.split(':');

  path.split('.').reduce((acc, prop, index, arr) => {
    const isLastProp = arr.length === index + 1;
    if (isLastProp) {
      acc[prop] = valueToChange;
    }

    return acc[prop];
  }, obj);
}

How would you implement the function replaceInObj?

  • I hope there's much-much simpler implementation.
  • And I would be grateful if you'd share your solution
bekliev
  • 2,331
  • 2
  • 12
  • 11
  • 1
    Questions on improving working code in terms of best practice, efficiency, readability, ... are better suited for [Code Review](https://codereview.stackexchange.com/). How anyone would *want* to do it, is a matter of opinion. – trincot Jul 02 '20 at 18:51
  • 1
    Oh, thanks! Didn't know that such an platform even existed - gonna post it to code-review then! – bekliev Jul 02 '20 at 18:53
  • 1
    "*How would you implement the function?*" - a bit of searching around with the right keywords will find you thousands of alternative solution for this quite common task, including [these](https://stackoverflow.com/q/18936915/1048572) – Bergi Jul 02 '20 at 19:14

1 Answers1

0

I think I found solution much cleaner and simpler to understand: https://codereview.stackexchange.com/a/240907/227075

That solution adjusted to my task

const testStr = 'bar.baz.foo:111222';
const testObj = {
  bar: {
    baz: {
      foo: '333444',
    },
  },
};

console.log('[before] testObj.bar.baz =', testObj.bar.baz);

// run
replaceInObj(testObj, testStr);

console.log('[after] testObj.bar.baz =', testObj.bar.baz);

function replaceInObj(obj, str) {
  const [path, valueToChange] = str.split(':');
  const properties = path.split('.');
  const lastProperty = properties.pop();
  const lastObject = properties.reduce((a, prop) => a[prop], obj);
  lastObject[lastProperty] = valueToChange;
}
bekliev
  • 2,331
  • 2
  • 12
  • 11