[tablex] Add rotate

This commit is contained in:
flamendless 2021-10-03 17:31:55 +08:00
parent 1d59b3623e
commit 8a069c38d4

View File

@ -61,6 +61,18 @@ function tablex.swap_and_pop(t, i)
return tablex.pop(t) return tablex.pop(t)
end end
--rotate the elements of a table by amount
function tablex.rotate(t, amount)
if amount == 0 then return t end
if amount > 0 then
tablex.push(t, tablex.shift(t))
return tablex.rotate(t, amount - 1)
elseif amount < 0 then
tablex.unshift(t, tablex.pop(t))
return tablex.rotate(t, amount + 1)
end
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)