aboutsummaryrefslogtreecommitdiffstats
path: root/util/array.lua
diff options
context:
space:
mode:
authorMatthew Wild <mwild1@gmail.com>2021-09-12 10:50:20 +0100
committerMatthew Wild <mwild1@gmail.com>2021-09-12 10:50:20 +0100
commitedb6956ad524febe58d5575d0bf42b4a7ddabc1c (patch)
tree444448cf660a0c4887605d6d3066648443b4cfbe /util/array.lua
parenteba0bacfdaeaddd47c323f6681c79d57228d93a5 (diff)
downloadprosody-edb6956ad524febe58d5575d0bf42b4a7ddabc1c.tar.gz
prosody-edb6956ad524febe58d5575d0bf42b4a7ddabc1c.zip
util.array: Add :slice() method + tests
Behaviour follows the same logic as string.sub (so yes, 1-indexed).
Diffstat (limited to 'util/array.lua')
-rw-r--r--util/array.lua34
1 files changed, 34 insertions, 0 deletions
diff --git a/util/array.lua b/util/array.lua
index 6e5c8383..c33a5ef1 100644
--- a/util/array.lua
+++ b/util/array.lua
@@ -114,6 +114,40 @@ function array_base.filter(outa, ina, func)
return outa;
end
+function array_base.slice(outa, ina, i, j)
+ if j == nil then
+ j = -1;
+ end
+ if j < 0 then
+ j = #ina + (j+1);
+ end
+ if i < 0 then
+ i = #ina + (i+1);
+ end
+ if i < 1 then
+ i = 1;
+ end
+ if j > #ina then
+ j = #ina;
+ end
+ if i > j then
+ for idx = 1, #outa do
+ outa[idx] = nil;
+ end
+ return outa;
+ end
+
+ for idx = 1, 1+j-i do
+ outa[idx] = ina[i+(idx-1)];
+ end
+ if ina == outa then
+ for idx = 2+j-i, #outa do
+ outa[idx] = nil;
+ end
+ end
+ return outa;
+end
+
function array_base.sort(outa, ina, ...)
if ina ~= outa then
outa:append(ina);