From 8a069c38d4293427993090b76dde98559356055f Mon Sep 17 00:00:00 2001 From: flamendless Date: Sun, 3 Oct 2021 17:31:55 +0800 Subject: [PATCH] [tablex] Add rotate --- tablex.lua | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tablex.lua b/tablex.lua index eb7f2e5..f147666 100644 --- a/tablex.lua +++ b/tablex.lua @@ -60,7 +60,19 @@ function tablex.swap_and_pop(t, i) tablex.swap(t, i, #t) return tablex.pop(t) 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 --(shared with sort.lua and suggests the sorted functions below should maybe be refactored there) local function default_less(a, b)