1

I would like to know if is possible to change attributes of an object passed to a function without mutating the state of the object.

Something like this:

function startOfLine(options) {
  options.someProp = += 'startOfLine';
  return options;
}

function otherFunction(options) {
  // do something with options and...
  return options;
}

const options = startOfLine(otherFunction({
  somePro: '',
  someProp2: ''
}));

I'm going to create the execution of the functions in a dynamic way, that's why i'm not worry about nesting 20 levels of calls.

Thanks.

  • 1
    What's the difference between "change" and "mutate" for you? You can hardly do one without the other. If you want immutability, you have to create a new object (with the nes state) and return that. – Bergi Jan 16 '17 at 23:57
  • Is it possible to measure the performance of creating an object in each function vs mutating the original? –  Jan 17 '17 at 00:00

2 Answers2

2

When you want to update an object in functional languages, the usual approach is to return a new cloned version of the object with some of the properties changes (without modifying the original object). I do not think there is a built-in way to clone object in JavaScript but this post provides a detailed answer. Using the clone function from that answer you can write:

function startOfLine(options) {
  var newOptions = clone(options);
  newOptions.someProp = 'startOfLine';
  return newOptions;
}

When you have object o1 and you write var o2 = startOfLine(o1) then you get back a new object o2 with startOfLine settings but without mutating o1.

If you are not mutating the object anywhere, you can perform shallow copy (and avoid cloning the entire object tree), but there is still some overhead involved - but you get the nice properties of working with immutable objects that often outweight the costs.

Community
  • 1
  • 1
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
0

Unfortunately, I do not have sufficient reputation to post a comment. So trying to answer based on some reasonable assumptions.

You are looking a way to chain some operations related a single object with better efficiency avoiding too much mutation or creation of new objects. The final object should the same object (or a copy?) with applied transformations.

If this is the one you are looking for, it can be done with a good memory efficiency by using Hash trees. You can refer to the library immutable.js by Facebook

https://facebook.github.io/immutable-js/

manikawnth
  • 2,739
  • 1
  • 25
  • 39