aboutsummaryrefslogtreecommitdiffstats
path: root/util/array.lua
diff options
context:
space:
mode:
authorKim Alvefur <zash@zash.se>2013-10-06 23:18:54 +0200
committerKim Alvefur <zash@zash.se>2013-10-06 23:18:54 +0200
commit087ed3fedce82fe59e6ed593ccf13928071d5e9e (patch)
tree0f8046043b011b7bcaf0a208ba684f7c840c43d3 /util/array.lua
parent662e6905a8bb18ff2a5b5f05549b4b64465af847 (diff)
downloadprosody-087ed3fedce82fe59e6ed593ccf13928071d5e9e.tar.gz
prosody-087ed3fedce82fe59e6ed593ccf13928071d5e9e.zip
util.array: Improve array:reverse() and make it work as both method and non-mutating function
Diffstat (limited to 'util/array.lua')
-rw-r--r--util/array.lua29
1 files changed, 20 insertions, 9 deletions
diff --git a/util/array.lua b/util/array.lua
index 9bf215af..6f2abe04 100644
--- a/util/array.lua
+++ b/util/array.lua
@@ -11,6 +11,7 @@ local t_insert, t_sort, t_remove, t_concat
local setmetatable = setmetatable;
local math_random = math.random;
+local math_floor = math.floor;
local pairs, ipairs = pairs, ipairs;
local tostring = tostring;
@@ -84,6 +85,25 @@ function array_base.pluck(outa, ina, key)
return outa;
end
+function array_base.reverse(outa, ina)
+ local len = #ina;
+ if ina == outa then
+ local middle = math_floor(len/2);
+ len = len + 1;
+ local o; -- opposite
+ for i = 1, middle do
+ o = len - i;
+ outa[i], outa[o] = outa[o], outa[i];
+ end
+ else
+ local off = len + 1;
+ for i = 1, len do
+ outa[i] = ina[off - i];
+ end
+ end
+ return outa;
+end
+
--- These methods only mutate the array
function array_methods:shuffle(outa, ina)
local len = #self;
@@ -94,15 +114,6 @@ function array_methods:shuffle(outa, ina)
return self;
end
-function array_methods:reverse()
- local len = #self-1;
- for i=len,1,-1 do
- self:push(self[i]);
- self:pop(i);
- end
- return self;
-end
-
function array_methods:append(array)
local len,len2 = #self, #array;
for i=1,len2 do