2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 local t_insert, t_sort, t_remove, t_concat
10 = table.insert, table.sort, table.remove, table.concat;
12 local setmetatable = setmetatable;
13 local math_random = math.random;
14 local pairs, ipairs = pairs, ipairs;
15 local tostring = tostring;
18 local array_base = {};
19 local array_methods = {};
20 local array_mt = { __index = array_methods, __tostring = function (array) return array:concat(", "); end };
22 local function new_array(_, t)
23 return setmetatable(t or {}, array_mt);
26 function array_mt.__add(a1, a2)
27 local res = new_array();
28 return res:append(a1):append(a2);
31 setmetatable(array, { __call = new_array });
34 function array_methods:random()
35 return self[math_random(1,#self)];
38 -- These methods can be called two ways:
39 -- array.method(existing_array, [params [, ...]]) -- Create new array for result
40 -- existing_array:method([params, ...]) -- Transform existing array into result
42 function array_base.map(outa, ina, func)
43 for k,v in ipairs(ina) do
49 function array_base.filter(outa, ina, func)
50 local inplace, start_length = ina == outa, #ina;
52 for read=1,start_length do
60 if inplace and write <= start_length then
61 for i=write,start_length do
69 function array_base.sort(outa, ina, ...)
77 function array_base.pluck(outa, ina, key)
79 outa[i] = ina[i][key];
84 --- These methods only mutate the array
85 function array_methods:shuffle(outa, ina)
88 local r = math_random(i,len);
89 self[i], self[r] = self[r], self[i];
94 function array_methods:reverse()
103 function array_methods:append(array)
104 local len,len2 = #self, #array;
106 self[len+i] = array[i];
111 function array_methods:push(x)
116 function array_methods:pop(x)
122 function array_methods:concat(sep)
123 return t_concat(array.map(self, tostring), sep);
126 function array_methods:length()
130 --- These methods always create a new array
131 function array.collect(f, s, var)
135 if var == nil then break; end
138 return setmetatable(t, array_mt);
143 -- Setup methods from array_base
144 for method, f in pairs(array_base) do
145 local base_method = f;
146 -- Setup global array method which makes new array
147 array[method] = function (old_a, ...)
148 local a = new_array();
149 return base_method(a, old_a, ...);
151 -- Setup per-array (mutating) method
152 array_methods[method] = function (self, ...)
153 return base_method(self, self, ...);