1

I'm trying to run this code and be able to "save" an object inside the "memory" array to view the past properties that the same object had after it changes.

this is the class:

class Circle {
radius;
center = {};
memory = [];

constructor(radius, x, y) {
    this.radius = radius;
    this.center.x = x;
    this.center.y = y;

moveX(steps) {
    if (!isNaN(steps)) {
        this.saveMemory(this);
        this.center.x += steps;
    }
    return this.center.x;
}
saveMemory(circle) {
    let temp = (({ memory, ...rest }) => rest)(circle);
    this.memory.push(temp);
}

when I view the memory array it shows the object after the x change.

var circle1 = new Circle(5, 1, 1);
circle1.moveX(2); // memory = [{radius:5,center{x:3,y:1})

How can I save the object before the changes were made?

edit: I want to get:

circle1.moveX(2); // memory = [{radius:5,center{x:1,y:1})
Baiden
  • 11
  • 2

2 Answers2

1
class Circle {
  radius;
  center = {};
  memory = [];

  constructor(radius, x, y) {
    this.radius = radius;
    this.center.x = x;
    this.center.y = y;
  }
  moveX(steps) {
    if (!isNaN(steps)) {
      this.saveMemory();
      this.center.x += steps;
    }
    return this.center.x;
  }
  saveMemory() {
    let { memory, ...rest } = this;
    this.memory.push(JSON.parse(JSON.stringify(rest)));
  }
}

var circle1 = new Circle(5, 1, 1);
circle1.moveX(2); // memory = [{radius:5,center{x:3,y:1})
circle1.moveX(6);
console.log(circle1.memory)

Heres a working implementation using JSON.stringify() to create a deep clone of your class attributes. Even with a shallow clone, the values stored in memory will be references to your circle object instead of copied data. This is the best way to do this as far as I can tell, though I hope someone corrects me. One of the nuances of dealing with JS classes.

There are other cloning alternatives as outlined here but in general this whole cloning stuff sucks.

SpeedOfRound
  • 1,210
  • 11
  • 26
  • Where do I implement the clone? `moveX(steps) { if (!isNaN(steps)) { var clonedObj = Object.assign({}, this); this.saveMemory(clonedObj); this.center.x += steps; } return this.center.x; }` I tried this but still the same. – Baiden Jan 14 '20 at 20:54
  • @Baiden see my edit – SpeedOfRound Jan 14 '20 at 21:33
0

That’s because the reference of the object you saved and updated is same. You need to store a cloned object into the memory.

var clonedObj = Object.assign({}, yourObj);
this.saveMemory(clonedObj);

This would do your job!

  • Where do I implement the clone? – Baiden Jan 14 '20 at 21:13
  • Just wherever you are calling saveMemory method, before calling save memory clone the object and then pass the cloned object to saveMemory method like I gave example. You can also make another function for it. – Muhammad Hassan Khan Jan 14 '20 at 21:17