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(self, t, _s, _var)
23 if type(t) == "function" then -- Assume iterator
24 t = self.collect(t, _s, _var);
26 return setmetatable(t or {}, array_mt);
29 function array_mt.__add(a1, a2)
30 local res = new_array();
31 return res:append(a1):append(a2);
34 setmetatable(array, { __call = new_array });
37 function array_methods:random()
38 return self[math_random(1,#self)];
41 -- These methods can be called two ways:
42 -- array.method(existing_array, [params [, ...]]) -- Create new array for result
43 -- existing_array:method([params, ...]) -- Transform existing array into result
45 function array_base.map(outa, ina, func)
46 for k,v in ipairs(ina) do
52 function array_base.filter(outa, ina, func)
53 local inplace, start_length = ina == outa, #ina;
55 for read=1,start_length do
63 if inplace and write <= start_length then
64 for i=write,start_length do
72 function array_base.sort(outa, ina, ...)
80 function array_base.pluck(outa, ina, key)
82 outa[i] = ina[i][key];
87 --- These methods only mutate the array
88 function array_methods:shuffle(outa, ina)
91 local r = math_random(i,len);
92 self[i], self[r] = self[r], self[i];
97 function array_methods:reverse()
106 function array_methods:append(array)
107 local len,len2 = #self, #array;
109 self[len+i] = array[i];
114 function array_methods:push(x)
119 function array_methods:pop(x)
125 function array_methods:concat(sep)
126 return t_concat(array.map(self, tostring), sep);
129 function array_methods:length()
133 --- These methods always create a new array
134 function array.collect(f, s, var)
138 if var == nil then break; end
141 return setmetatable(t, array_mt);
146 -- Setup methods from array_base
147 for method, f in pairs(array_base) do
148 local base_method = f;
149 -- Setup global array method which makes new array
150 array[method] = function (old_a, ...)
151 local a = new_array();
152 return base_method(a, old_a, ...);
154 -- Setup per-array (mutating) method
155 array_methods[method] = function (self, ...)
156 return base_method(self, self, ...);