I'm building a simple backup/undo functionality and failing to correctly clone an array to put into the backup. I've tried using slice()
and a recursive function to "deep clone", but either the cloned array remains a copy of the latest state or it does not clone all the elements of the array.
I'm using Babel.
constructor(config) {
this.all = [];
this.all.colors = [5,7];
this.all.sprites = [];
this.all.current_sprite = 0;
this.all.width = config.sprite_x;
this.all.height = config.sprite_y;
this.backup = [];
this.backup_position = 0;
}
Version 1 deep clone (does not work)
save_backup() {
this.backup.push(this.deepClone(this.all));
this.backup_position ++;
console.log(this.backup);
}
deepClone(arr) {
var len = arr.length;
var newArr = new Array(len);
for (var i=0; i<len; i++) {
if (Array.isArray(arr[i])) {
newArr[i] = deepClone(arr[i]);
} else {
newArr[i] = arr[i];
}
}
return newArr;
}
Version 2 slice()
(does not work).
save_backup() {
this.backup.push(this.all.slice());
this.backup_position ++;
console.log(this.backup);
}
The array contains all kinds of data: integers, arrays, objects, like
colors : (2) [5, 7]
config : {setting: "c64", sprite_x: 24, sprite_y: 21, colors: Array(16), zoom: 20, …}
What am I doing wrong? Thanks a lot for your help.