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 math_floor = math.floor;
15 local pairs, ipairs = pairs, ipairs;
16 local tostring = tostring;
19 local array_base = {};
20 local array_methods = {};
21 local array_mt = { __index = array_methods, __tostring = function (array) return "{"..array:concat(", ").."}"; end };
23 local function new_array(self, t, _s, _var)
24 if type(t) == "function" then -- Assume iterator
25 t = self.collect(t, _s, _var);
27 return setmetatable(t or {}, array_mt);
30 function array_mt.__add(a1, a2)
31 local res = new_array();
32 return res:append(a1):append(a2);
35 setmetatable(array, { __call = new_array });
38 function array_methods:random()
39 return self[math_random(1,#self)];
42 -- These methods can be called two ways:
43 -- array.method(existing_array, [params [, ...]]) -- Create new array for result
44 -- existing_array:method([params, ...]) -- Transform existing array into result
46 function array_base.map(outa, ina, func)
47 for k,v in ipairs(ina) do
53 function array_base.filter(outa, ina, func)
54 local inplace, start_length = ina == outa, #ina;
56 for read=1,start_length do
64 if inplace and write <= start_length then
65 for i=write,start_length do
73 function array_base.sort(outa, ina, ...)
81 function array_base.pluck(outa, ina, key)
83 outa[i] = ina[i][key];
88 function array_base.reverse(outa, ina)
91 local middle = math_floor(len/2);
96 outa[i], outa[o] = outa[o], outa[i];
101 outa[i] = ina[off - i];
107 --- These methods only mutate the array
108 function array_methods:shuffle(outa, ina)
111 local r = math_random(i,len);
112 self[i], self[r] = self[r], self[i];
117 function array_methods:append(array)
118 local len,len2 = #self, #array;
120 self[len+i] = array[i];
125 function array_methods:push(x)
130 function array_methods:pop(x)
136 function array_methods:concat(sep)
137 return t_concat(array.map(self, tostring), sep);
140 function array_methods:length()
144 --- These methods always create a new array
145 function array.collect(f, s, var)
149 if var == nil then break; end
152 return setmetatable(t, array_mt);
157 -- Setup methods from array_base
158 for method, f in pairs(array_base) do
159 local base_method = f;
160 -- Setup global array method which makes new array
161 array[method] = function (old_a, ...)
162 local a = new_array();
163 return base_method(a, old_a, ...);
165 -- Setup per-array (mutating) method
166 array_methods[method] = function (self, ...)
167 return base_method(self, self, ...);