-
-
Notifications
You must be signed in to change notification settings - Fork 331
Expand file tree
/
Copy pathstructs.lua
More file actions
119 lines (100 loc) · 2.38 KB
/
structs.lua
File metadata and controls
119 lines (100 loc) · 2.38 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
---@class PlenaryAsyncStructs
local M = {}
---A double ended queue
---@class PlenaryDeque
---@field first integer
---@field last integer
---@field [integer] any
local Deque = {}
Deque.__index = Deque
---@return PlenaryDeque
function Deque.new()
-- the indexes are created with an offset so that the indices are consequtive
-- otherwise, when both pushleft and pushright are used, the indices will have a 1 length hole in the middle
return setmetatable({ first = 0, last = -1 }, Deque)
end
---push to the left of the deque
---@param value any
function Deque:pushleft(value)
local first = self.first - 1
self.first = first
self[first] = value
end
---push to the right of the deque
---@param value any
function Deque:pushright(value)
local last = self.last + 1
self.last = last
self[last] = value
end
---pop from the left of the deque
---@return any
function Deque:popleft()
local first = self.first
if first > self.last then
return nil
end
local value = self[first]
self[first] = nil -- to allow garbage collection
self.first = first + 1
return value
end
---pops from the right of the deque
---@return any
function Deque:popright()
local last = self.last
if self.first > last then
return nil
end
local value = self[last]
self[last] = nil -- to allow garbage collection
self.last = last - 1
return value
end
---checks if the deque is empty
---@return boolean
function Deque:is_empty()
return self:len() == 0
end
---returns the number of elements of the deque
---@return integer
function Deque:len()
return self.last - self.first + 1
end
---returns and iterator of the indices and values starting from the left
---@return fun(): integer?, any?
function Deque:ipairs_left()
local i = self.first
return function()
local res = self[i]
local idx = i
if res then
i = i + 1
return idx, res
end
end
end
---returns and iterator of the indices and values starting from the right
---@return fun(): integer?, any?
function Deque:ipairs_right()
local i = self.last
return function()
local res = self[i]
local idx = i
if res then
i = i - 1 -- advance the iterator before we return
return idx, res
end
end
end
---removes all values from the deque
---@return nil
function Deque:clear()
for i, _ in self:ipairs_left() do
self[i] = nil
end
self.first = 0
self.last = -1
end
M.Deque = Deque
return M