-
Notifications
You must be signed in to change notification settings - Fork 1
/
Changes.lua
99 lines (87 loc) · 1.79 KB
/
Changes.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
local class = require("class")
---@class util.Changes
---@operator call: util.Changes
local Changes = class()
function Changes:new()
self[1] = 0
self.index = 2
end
---@return number
function Changes:get()
local i = self.index
return self[i] or self[i - 1] or 0
end
---@return number
function Changes:add()
local i = self.index
self[i] = self:get() + 1
return self[i]
end
---@return number
function Changes:next()
if not self[self.index] then
return self:get()
end
self.index = self.index + 1
return self:get()
end
function Changes:reset()
for i = self.index, #self do
self[i] = nil
end
end
---@param _changes util.Changes
---@param index number
---@return number?
local function undo(_changes, index)
local changeStart, changeEnd = _changes[_changes.index - 1], _changes[_changes.index - 2]
if not changeEnd then
return
end
index = (index or changeStart + 1) - 1
if index == changeEnd then
_changes.index = _changes.index - 1
return
end
return index
end
---@param _changes util.Changes
---@param index number
---@return number?
local function redo(_changes, index)
local changeStart, changeEnd = _changes[_changes.index - 1], _changes[_changes.index]
if not changeEnd then
return
end
index = (index or changeStart) + 1
if index == changeEnd + 1 then
_changes.index = _changes.index + 1
return
end
return index
end
---@return function
---@return util.Changes
function Changes:undo()
return undo, self
end
---@return function
---@return util.Changes
function Changes:redo()
return redo, self
end
---@return string
function Changes:__tostring()
local t = {}
for i = 1, #self do
t[i] = self[i]
if i == self.index then
t[i] = ("[%s]"):format(self[i])
end
end
if self.index > #self then
t[self.index] = "[_]"
end
return table.concat(t, ",")
end
return Changes