Merge feature/tablex.rotate

refactored to use loops instead of recursion for simplicity
This commit is contained in:
Max Cahill 2021-10-08 10:17:34 +11:00
commit 0a02d7a2da

View File

@ -61,6 +61,23 @@ function tablex.swap_and_pop(t, i)
return tablex.pop(t) return tablex.pop(t)
end end
--rotate the elements of a table t by amount slots
-- amount 1: {1, 2, 3, 4} -> {2, 3, 4, 1}
-- amount -1: {1, 2, 3, 4} -> {4, 1, 2, 3}
function tablex.rotate(t, amount)
if #t > 1 then
while amount > 0 do
tablex.push(t, tablex.shift(t))
amount = amount - 1
end
while amount < 0 do
tablex.unshift(t, tablex.pop(t))
amount = amount + 1
end
end
return t
end
--default comparison; hoisted for clarity --default comparison; hoisted for clarity
--(shared with sort.lua and suggests the sorted functions below should maybe be refactored there) --(shared with sort.lua and suggests the sorted functions below should maybe be refactored there)
local function default_less(a, b) local function default_less(a, b)