diff --git a/ngcp/utils.lua b/ngcp/utils.lua index e7dad5a..281d4ad 100644 --- a/ngcp/utils.lua +++ b/ngcp/utils.lua @@ -120,6 +120,40 @@ function table.shuffle(tab) return res end +-- range(start) returns an iterator from 1 to a (step = 1) +-- range(start, stop) returns an iterator from a to b (step = 1) +-- range(start, stop, step) returns an iterator from a to b, counting by step. +range = function (i, to, inc) + -- range(--[[ no args ]]) -> return "nothing" to fail the loop in the caller + if i == nil then return end + + if not to then + to = i + i = to == 0 and 0 or (to > 0 and 1 or -1) + end + + -- we don't have to do the to == 0 check + -- 0 -> 0 with any inc would never iterate + inc = inc or (i < to and 1 or -1) + + -- step back (once) before we start + i = i - inc + + return function () if i == to then return nil end i = i + inc return i, i end +end + +function table.shift(t, positions) + local k, v + local res = {} + for k in range(1, positions % #t) do + v = table.remove(t, k-#res) + table.insert(res, v) + end + for _,v in ipairs(res) do + table.insert(t, v) + end +end + -- from table to string -- t = {'a','b'} -- implode(",",t,"'") diff --git a/tests/utils.lua b/tests/utils.lua index e2cde01..b8f28bd 100644 --- a/tests/utils.lua +++ b/tests/utils.lua @@ -73,6 +73,21 @@ TestUtils = {} --class assertNotEquals(tmp2, tmp) end + function TestUtils:test_table_shift() + assertEquals(self.simple_list, {1,2,3}) + table.add(self.simple_list, 4) + table.add(self.simple_list, 5) + table.add(self.simple_list, 6) + table.shift(self.simple_list, 2) + assertEquals(self.simple_list, {3,4,5,6,1,2}) + end + + function TestUtils:test_table_shift2() + assertEquals(self.simple_list, {1,2,3}) + table.shift(self.simple_list, 4) + assertEquals(self.simple_list, {2,3,1}) + end + function TestUtils:test_table_tostring() assertError(table.tostring,nil) assertEquals(table.tostring(self.simple_list), "{1,2,3}")