1
-- deque from https://github.com/catwell/cw-lua/tree/master/deque
4
local push_right = function(self, x)
6
self.tail = self.tail + 1
10
local push_left = function(self, x)
13
self.head = self.head - 1
16
local peek_right = function(self)
17
return self[self.tail]
20
local peek_left = function(self)
21
return self[self.head+1]
24
local pop_right = function(self)
25
if self:is_empty() then return nil end
26
local r = self[self.tail]
28
self.tail = self.tail - 1
32
local pop_left = function(self)
33
if self:is_empty() then return nil end
34
local r = self[self.head+1]
35
self.head = self.head + 1
36
local r = self[self.head]
41
local rotate_right = function(self, n)
43
if self:is_empty() then return nil end
44
for i=1,n do self:push_left(self:pop_right()) end
47
local rotate_left = function(self, n)
49
if self:is_empty() then return nil end
50
for i=1,n do self:push_right(self:pop_left()) end
53
local _remove_at_internal = function(self, idx)
54
for i=idx, self.tail do self[i] = self[i+1] end
55
self.tail = self.tail - 1
58
local remove_right = function(self, x)
59
for i=self.tail,self.head+1,-1 do
61
_remove_at_internal(self, i)
68
local remove_left = function(self, x)
69
for i=self.head+1,self.tail do
71
_remove_at_internal(self, i)
78
local length = function(self)
79
return self.tail - self.head
82
local is_empty = function(self)
83
return self:length() == 0
86
local contents = function(self)
88
for i=self.head+1,self.tail do
89
r[i-self.head] = self[i]
94
local iter_right = function(self)
97
if i > self.head+1 then
104
local iter_left = function(self)
107
if i < self.tail then
115
push_right = push_right,
116
push_left = push_left,
117
peek_right = peek_right,
118
peek_left = peek_left,
119
pop_right = pop_right,
121
rotate_right = rotate_right,
122
rotate_left = rotate_left,
123
remove_right = remove_right,
124
remove_left = remove_left,
125
iter_right = iter_right,
126
iter_left = iter_left,
132
local new = function()
133
local r = {head=0,tail=0}
134
return setmetatable(r, {__index=methods})