aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatthew Wild <mwild1@gmail.com>2011-12-07 05:14:58 +0000
committerMatthew Wild <mwild1@gmail.com>2011-12-07 05:14:58 +0000
commitf1f40bc3ca38cf67e38bcf844a6d99a9a4f9e9bb (patch)
tree65d62f327ab3465a6acdc5529503ed558eca772d
parentf1f5f74ad3c9b66cf60b5e86b5fc12afe52a448b (diff)
downloadprosody-f1f40bc3ca38cf67e38bcf844a6d99a9a4f9e9bb.tar.gz
prosody-f1f40bc3ca38cf67e38bcf844a6d99a9a4f9e9bb.zip
util.array: Expand some of the more basic methods to act more sensibly than their names suggested
-rw-r--r--util/array.lua36
1 files changed, 27 insertions, 9 deletions
diff --git a/util/array.lua b/util/array.lua
index cf586214..cbb051d3 100644
--- a/util/array.lua
+++ b/util/array.lua
@@ -25,6 +25,15 @@ end
setmetatable(array, { __call = new_array });
+-- Read-only methods
+function array_methods:random()
+ return self[math.random(1,#self)];
+end
+
+-- These methods can be called two ways:
+-- array.method(existing_array, [params [, ...]]) -- Create new array for result
+-- existing_array:method([params, ...]) -- Transform existing array into result
+--
function array_base.map(outa, ina, func)
for k,v in ipairs(ina) do
outa[k] = func(v);
@@ -67,11 +76,7 @@ function array_base.pluck(outa, ina, key)
return outa;
end
---- These methods only mutate
-function array_methods:random()
- return self[math.random(1,#self)];
-end
-
+--- These methods only mutate the array
function array_methods:shuffle(outa, ina)
local len = #self;
for i=1,#self do
@@ -98,10 +103,23 @@ function array_methods:append(array)
return self;
end
-array_methods.push = table.insert;
-array_methods.pop = table.remove;
-array_methods.concat = table.concat;
-array_methods.length = function (t) return #t; end
+function array_methods:push(x)
+ table.insert(self, x);
+end
+
+function array_methods:pop(x)
+ local v = self[x];
+ table.remove(self, x);
+ return v;
+end
+
+function array_methods:concat(sep)
+ return table.concat(array.map(self, tostring), sep);
+end
+
+function array_methods:length()
+ return #self;
+end
--- These methods always create a new array
function array.collect(f, s, var)