How to prevent mutation of an object / array

I tried to debug a weird problem, and I finally figured out why this is happening. Just not sure how to prevent this (I have this function:

getInfo(id) {
  id = id || "zero";
  let i = routeDefinitions.findIndex(r => Boolean(r.name.toLowerCase().match(id)));
  // console.log(i) - works in plunker
  // but in my app sometimes returns -1...
  let current = routeDefinitions[i];
  let next = routeDefinitions[i + 1] ? routeDefinitions[i + 1] : false;
  let prev = routeDefinitions[i - 1] ? routeDefinitions[i - 1] : false;
  return { prev, current, next };
}

.. it works fine in this plunker , but in my application I use its return value to update the state of the application (custom implementation of the reduction template). When I send the return value through this function:

  private _update(_old, _new) {
    let newState = Object.keys(_new)
      .map(key => {
        if (_old[key] === undefined) {
          _old[key] = _new[key];
        } else if (typeof _new[key] === "object") {
          this._update(_old[key], _new[key]);
        } else {
          _old[key] = _new[key];
        }
        return _old;
      })
      .find(Boolean);

    return Object.assign({}, newState || _old);
  }

.. the routeDefinitionsarray is mutated, and everything starts to break ... I tried a couple of things:

let current = [...routeDefinitions][i];
// and:
return Object.assign({}, { prev, current, next });

.. but that didn't work. How to prevent mutation of an array routeDefinitions?

EDIT : I was able to reproduce the error in this plunker

+4
2

, _update() :

  private _update2(_old, _new) {
    let newState = {}; 
    Object.keys(_new)
      .map(key => {
        if (_old[key] === undefined) {
          newState[key] = _new[key];
        } else if (typeof _new[key] === "object") {
          newState[key] = this._update2(_old[key], _new[key]);
        } else {
          newState[key] = _new[key];
        }
        return newState;
      })
      .find(Boolean);

    return Object.assign({}, _old, newState);
  } 

old state , , _update().

Plunker

0

routeDefinitions ,

:

getInfo(id) {
  id = id || "zero";
  let i = routeDefinitions.findIndex(r => Boolean(r.name.toLowerCase().match(id)));
  // console.log(i) - works in plunker
  // but in my app sometimes returns -1...
  let current = routeDefinitions[i];
  let next = routeDefinitions[i + 1] ? routeDefinitions[i + 1] : false;
  let prev = routeDefinitions[i - 1] ? routeDefinitions[i - 1] : false;
  return { prev, current, next };
}

routeDefinitions . - mutating routeDefinitions.

0

Source: https://habr.com/ru/post/1624669/


All Articles