dot-object icon indicating copy to clipboard operation
dot-object copied to clipboard

Mutation of parameter in object function

Open coderaiser opened this issue 9 years ago • 2 comments

Would be great if object function do not mutate obj parameter:

You can use Object.assign for this purpose in:

DotObject.prototype.object = function (obj, mods) {
  var self = this

  obj = Object.assign({}, obj); // prevent mutation

  Object.keys(obj).forEach(function (k) {
    var mod = mods === undefined ? null : mods[k]
    // normalize array notation.
    var ok = parsePath(k, self.seperator).join(self.seperator)

    if (ok.indexOf(self.seperator) !== -1) {
      self._fill(ok.split(self.seperator), obj, obj[k], mod)
      delete obj[k]
    } else if (self.override) {
      obj[k] = _process(obj[k], mod)
    }
  })

  return obj
}

coderaiser avatar Apr 01 '16 09:04 coderaiser

This would break the current behavior. You'll have to call Object.assign before you pass it into .object()

I could add another method doing this for you or make it an option, not sure what that method would have to be named though. object itself is a rather cryptic name, so a new one wouldn't hurt.

rhalff avatar Apr 02 '16 21:04 rhalff

This would break the current behavior.

You can increase major version. If you already return obj in your function, what is the reason to mutate parameter object? What profit? Pure functions has a lot advantages.

You'll have to call Object.assign before you pass it into .object()

That is what I'm doing now, actually. The thing is this unpredictable behavior leads to bugs that are difficult to detect.

coderaiser avatar Apr 04 '16 06:04 coderaiser