blob: e7b774bbc82700e21e77009719b7f01e33b571d4 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
local print = print;
local t_insert = table.insert;
local t_sort = table.sort;
module "mtools"
function sorted(params)
local reader = params.reader; -- iterator to get items from
local sorter = params.sorter; -- sorting function
local filter = params.filter; -- filter function
local cache = {};
for item in reader do
if filter then item = filter(item); end
if item then t_insert(cache, item); end
end
if sorter then
t_sort(cache, sorter);
end
local i = 0;
return function()
i = i + 1;
return cache[i];
end;
end
function merged(reader, merger)
local item1 = reader();
local merged = { item1 };
return function()
while true do
if not item1 then return nil; end
local item2 = reader();
if not item2 then item1 = nil; return merged; end
if merger(item1, item2) then
--print("merged")
item1 = item2;
t_insert(merged, item1);
else
--print("unmerged", merged)
item1 = item2;
local tmp = merged;
merged = { item1 };
return tmp;
end
end
end;
end
return _M;
|