Software /
code /
prosody
Comparison
util/array.lua @ 4440:c60ed6732b34
util.array: Expand some of the more basic methods to act more sensibly than their names suggested
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Wed, 07 Dec 2011 05:14:58 +0000 |
parent | 4439:1c8d2c0d02db |
child | 4448:d745f4c28294 |
comparison
equal
deleted
inserted
replaced
4439:1c8d2c0d02db | 4440:c60ed6732b34 |
---|---|
23 return res:append(a1):append(a2); | 23 return res:append(a1):append(a2); |
24 end | 24 end |
25 | 25 |
26 setmetatable(array, { __call = new_array }); | 26 setmetatable(array, { __call = new_array }); |
27 | 27 |
28 -- Read-only methods | |
29 function array_methods:random() | |
30 return self[math.random(1,#self)]; | |
31 end | |
32 | |
33 -- These methods can be called two ways: | |
34 -- array.method(existing_array, [params [, ...]]) -- Create new array for result | |
35 -- existing_array:method([params, ...]) -- Transform existing array into result | |
36 -- | |
28 function array_base.map(outa, ina, func) | 37 function array_base.map(outa, ina, func) |
29 for k,v in ipairs(ina) do | 38 for k,v in ipairs(ina) do |
30 outa[k] = func(v); | 39 outa[k] = func(v); |
31 end | 40 end |
32 return outa; | 41 return outa; |
65 outa[i] = ina[i][key]; | 74 outa[i] = ina[i][key]; |
66 end | 75 end |
67 return outa; | 76 return outa; |
68 end | 77 end |
69 | 78 |
70 --- These methods only mutate | 79 --- These methods only mutate the array |
71 function array_methods:random() | |
72 return self[math.random(1,#self)]; | |
73 end | |
74 | |
75 function array_methods:shuffle(outa, ina) | 80 function array_methods:shuffle(outa, ina) |
76 local len = #self; | 81 local len = #self; |
77 for i=1,#self do | 82 for i=1,#self do |
78 local r = math.random(i,len); | 83 local r = math.random(i,len); |
79 self[i], self[r] = self[r], self[i]; | 84 self[i], self[r] = self[r], self[i]; |
96 self[len+i] = array[i]; | 101 self[len+i] = array[i]; |
97 end | 102 end |
98 return self; | 103 return self; |
99 end | 104 end |
100 | 105 |
101 array_methods.push = table.insert; | 106 function array_methods:push(x) |
102 array_methods.pop = table.remove; | 107 table.insert(self, x); |
103 array_methods.concat = table.concat; | 108 end |
104 array_methods.length = function (t) return #t; end | 109 |
110 function array_methods:pop(x) | |
111 local v = self[x]; | |
112 table.remove(self, x); | |
113 return v; | |
114 end | |
115 | |
116 function array_methods:concat(sep) | |
117 return table.concat(array.map(self, tostring), sep); | |
118 end | |
119 | |
120 function array_methods:length() | |
121 return #self; | |
122 end | |
105 | 123 |
106 --- These methods always create a new array | 124 --- These methods always create a new array |
107 function array.collect(f, s, var) | 125 function array.collect(f, s, var) |
108 local t = {}; | 126 local t = {}; |
109 while true do | 127 while true do |