documentcloud / underscore-contrib

The brass buckles on Underscore's utility belt
MIT License
621 stars 117 forks source link

_.setPath is not mutating the obj argument. #184

Closed martincastell closed 9 years ago

martincastell commented 9 years ago

According to the docs, _.setPath:

Sets the value of a property at any depth in obj based on the path described by the ks array. If any of the properties in the ks path don't exist, they will be created with defaultValue.

See _.updatePath about obj not being mutated in the process by cloning it.

Using .updatePath would create a copy, it sounds like .setPath should modify the original object, but it's not happening right now. JSFiddle: http://jsfiddle.net/ds2qa8bc/1/

DarrenN commented 9 years ago

On line 5 - if you add a console.log:

console.log(_.setPath(myObj, 'after', ['level1', 'level2', 'level3'], {}));

You'll see that setPath returns a new object with the updated property.

martincastell commented 9 years ago

I see that, but from the docs it sounds to me like .setPath modifies the object and .updatePath creates a copy (like _.setPath is doing right now).

See _.updatePath about obj not being mutated in the process by cloning it.
codelahoma commented 9 years ago

@martincastell:

Both _.setPath and _.updatePath return new objects without mutating the one passed to them (they're both in the object.builders sub-library, after all).

Looking at the source, _.setPath actually calls _.updatePath to get its work done.

The documentation you quoted is awkwardly worded. I believe the intent was to say that the lack of object mutation mentioned in the _.updatePath documentation applies to _.setPath as well, which it does.

I'll try to clarify the doc and submit a PR.