history.go 556 B

123456789101112131415161718192021222324252627282930313233343536
  1. package history
  2. type History[T any] struct {
  3. elements []T
  4. index int
  5. }
  6. func (h *History[T]) Current() T {
  7. return h.elements[h.index]
  8. }
  9. func (h *History[T]) Back() {
  10. if h.index > 0 {
  11. h.index -= 1
  12. }
  13. }
  14. func (h *History[T]) Forward() {
  15. if len(h.elements) > h.index+1 {
  16. h.index += 1
  17. }
  18. }
  19. func (h *History[T]) Add(element T) {
  20. if h.elements == nil {
  21. h.elements = []T{element}
  22. h.index = 0
  23. return
  24. }
  25. h.elements = append(h.elements[:h.index+1], element)
  26. h.index += 1
  27. }
  28. func (h *History[T]) IsEmpty() bool {
  29. return len(h.elements) == 0
  30. }