I have a js game editor, and in order for it to have the undo function, I need to store the last couple states of the editors map. I need it to only push previous maps to stack if they are different form the first map on the stack, which means that maps will be pushed only when they are not the same as the last one. This stops copy maps from being pushed every frame, using up all the space in the stack, and having to undo tens of times to get back to where the human perception of the last state was.
At first, I thought it would be easy, just save the start
condition of the map, do stuff, then save the end
condition. If they are different, the user changed something, and the start condition should be push onto the stack. To undo, just set the current map to the last thing on the stack.
The problem is that some of these arrays seem to be linked, and are tripping up my function to check if they are equal.
//This code is part of the method that handles the mouse,
//inside the editor class:
let start = this.map.slice(0);
//DO STUFF
let end = this.map.slice(0);
if(!ArrayIsEqual2d(start, end)){
console.log('changed')
this.lastMaps.unshift(start);
if(this.lastMaps.length > this.undoBuffer){
this.lastMaps.pop();
}
}
//End code inside of editor class
function ArrayIsEqual2d(one, two){
if(one == null || two == null || one == undefined || two == undefined){
return false;
}
if(one.length !== two.length){
return false;
}
for(let i = 0; i < one.length; i++){
if(one[i].length !== two[i].length){
return false;
}
for(let j = 0; j < one[i].length; j++){
if(one[i][j] !== two[i][j]){
return false;
}
}
}
return true;
}
The behavior is really weird, and it never detects that the map was changed, whats stranger is when I expose the start
and end
to the console, the value of start depends on where I log it. If it is logged right after it is created (before the user does stuff), its value is different then when I log it at the same time as end (after the user does stuff). Whenever I log it after the user does stuff, its value is always the same as map
, which means that start
and end
are always the same during the check to see if anything has changed.
The only thing I could think of was that it was due to linking, but adding the .slice(0)
in there changes nothing