Last active
July 30, 2018 09:08
-
-
Save ha1f/ee0e3da7441d805fefbda72180187bdd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class History<T> { | |
// MARK: Properties | |
private var _undoStack: [T] = [] | |
private var _redoStack: [T] = [] | |
private var _current: T | |
// MARK: Getter, Setter | |
var current: T { | |
get { | |
return _current | |
} | |
set { | |
_undoStack.append(current) | |
_current = newValue | |
_redoStack = [] | |
} | |
} | |
var canUndo: Bool { | |
return !_undoStack.isEmpty | |
} | |
var canRedo: Bool { | |
return !_redoStack.isEmpty | |
} | |
// MARK: Initializers | |
init(state: T) { | |
self._current = state | |
} | |
// MARK: Functions | |
func undo() { | |
guard let nextState = _undoStack.popLast() else { | |
return | |
} | |
_redoStack.append(_current) | |
_current = nextState | |
} | |
func redo() { | |
guard let nextState = _redoStack.popLast() else { | |
return | |
} | |
_undoStack.append(_current) | |
_current = nextState | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment