Comparison

util/array.lua @ 5857:8613888d0f9e

util.array: Improve array:reverse() and make it work as both method and non-mutating function
author Kim Alvefur <zash@zash.se>
date Sun, 06 Oct 2013 23:18:54 +0200
parent 5776:bd0ff8ae98a8
child 6417:060b63a27e9b
comparison
equal deleted inserted replaced
5856:e3e593eb81d1 5857:8613888d0f9e
9 local t_insert, t_sort, t_remove, t_concat 9 local t_insert, t_sort, t_remove, t_concat
10 = table.insert, table.sort, table.remove, table.concat; 10 = table.insert, table.sort, table.remove, table.concat;
11 11
12 local setmetatable = setmetatable; 12 local setmetatable = setmetatable;
13 local math_random = math.random; 13 local math_random = math.random;
14 local math_floor = math.floor;
14 local pairs, ipairs = pairs, ipairs; 15 local pairs, ipairs = pairs, ipairs;
15 local tostring = tostring; 16 local tostring = tostring;
16 17
17 local array = {}; 18 local array = {};
18 local array_base = {}; 19 local array_base = {};
82 outa[i] = ina[i][key]; 83 outa[i] = ina[i][key];
83 end 84 end
84 return outa; 85 return outa;
85 end 86 end
86 87
88 function array_base.reverse(outa, ina)
89 local len = #ina;
90 if ina == outa then
91 local middle = math_floor(len/2);
92 len = len + 1;
93 local o; -- opposite
94 for i = 1, middle do
95 o = len - i;
96 outa[i], outa[o] = outa[o], outa[i];
97 end
98 else
99 local off = len + 1;
100 for i = 1, len do
101 outa[i] = ina[off - i];
102 end
103 end
104 return outa;
105 end
106
87 --- These methods only mutate the array 107 --- These methods only mutate the array
88 function array_methods:shuffle(outa, ina) 108 function array_methods:shuffle(outa, ina)
89 local len = #self; 109 local len = #self;
90 for i=1,#self do 110 for i=1,#self do
91 local r = math_random(i,len); 111 local r = math_random(i,len);
92 self[i], self[r] = self[r], self[i]; 112 self[i], self[r] = self[r], self[i];
93 end
94 return self;
95 end
96
97 function array_methods:reverse()
98 local len = #self-1;
99 for i=len,1,-1 do
100 self:push(self[i]);
101 self:pop(i);
102 end 113 end
103 return self; 114 return self;
104 end 115 end
105 116
106 function array_methods:append(array) 117 function array_methods:append(array)