As part of a screening process, I was sent a TestDome link to assess my Data structure Prowess. The question goes like this,
“Modify the implementation of the Snapshot class so that an Array stored
in the snapshot is not affected by modifications to either the original or restored Array.“
This is the original Javascript code
var array = [1, 2];
var snap = new Snapshot(array);
array[0] = 3;
array = snap.restore();
console.log(array.join()); //It should log "1,2"
array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2"
At this point, it logs
3,2
3,2,4
to the console. but the goal is for the console to log 1, 2 and 1, 2 both times
I understand for the array in the constructor to remain unchanged, I need to copy and array and transfer all computations to the copied array for that class instance.
Now, this is what I did, I converted the array to integer and stored it in a new variable.
var array = [1, 2];
var result = array.map((x) => {return parseInt(x, 10); }); //line I added
var snap = new Snapshot(result); // changed snapshot parameter to result
array[0] = 3;
array = snap.restore();
console.log(array.join()); //It should log "1,2"
array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2"
Now the problem is it logs 1,2 and 1, 2, 4 to the console
I don’t get why snap doesn’t restore to before the push method. Or maybe my whole approach was wrong.
Please don’t just answer with the correct code. I wish to understand your thought process as well.