Nice article. I have one question, though. Why are you using splice in this._stack.splice(nextID, this._stack.length - nextID, data); and not push i.e. this._stack.push(data);? For me it's seems way more complicated to do all that in order to only add new element as the last element of the Array.
It's subtle but we actually want to remove all elements after nextID.
Let's say I do three actions.. 1, 2, 3. I now have three (well four, if you include initial state) states on my stack.
If I undo two of those (3 and 2), my current state will be action 1. But I'm able to redo those two by typing Ctrl-Shift-Z.
I'm also able do perform another action, which would invalidate those previous states, because I can no longer redo them. That's what the splice is doing—removing the rest of the stack and pushing a new state on.
I hope that explanation helps!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Nice article. I have one question, though. Why are you using
splice
inthis._stack.splice(nextID, this._stack.length - nextID, data);
and notpush
i.e.this._stack.push(data);
? For me it's seems way more complicated to do all that in order to only add new element as the last element of the Array.Good question!
It's subtle but we actually want to remove all elements after
nextID
.Let's say I do three actions.. 1, 2, 3. I now have three (well four, if you include initial state) states on my stack.
If I undo two of those (3 and 2), my current state will be action 1. But I'm able to redo those two by typing
Ctrl-Shift-Z
.I'm also able do perform another action, which would invalidate those previous states, because I can no longer redo them. That's what the splice is doing—removing the rest of the stack and pushing a new state on.
I hope that explanation helps!