aboutsummaryrefslogtreecommitdiffstats
path: root/util/iterators.lua
blob: 08bb729c63f63a2331213c310dfc8026ee5beac6 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
-- 
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--

--[[ Iterators ]]--

-- Reverse an iterator
function reverse(f, s, var)
	local results = {};

	-- First call the normal iterator
	while true do
		local ret = { f(s, var) };
		var = ret[1];
	        if var == nil then break; end
		table.insert(results, 1, ret);
	end
	
	-- Then return our reverse one
	local i,max = 0, #results;
	return function (results)
			if i<max then
				i = i + 1;
				return unpack(results[i]);
			end
		end, results;
end

-- Iterate only over keys in a table
local function _keys_it(t, key)
	return (next(t, key));
end
function keys(t)
	return _keys_it, t;
end

-- Iterate only over values in a table
function values(t)
	local key, val;
	return function (t)
		key, val = next(t, key);
		return val;
	end, t;
end

-- Given an iterator, iterate only over unique items
function unique(f, s, var)
	local set = {};
	
	return function ()
		while true do
			local ret = { f(s, var) };
			var = ret[1];
		        if var == nil then break; end
		        if not set[var] then
				set[var] = true;
				return var;
			end
		end
	end;
end

--[[ Return the number of items an iterator returns ]]--
function count(f, s, var)
	local x = 0;
	
	while true do
		local ret = { f(s, var) };
		var = ret[1];
	        if var == nil then break; end
		x = x + 1;
	end	
	
	return x;
end

-- Convert the values returned by an iterator to an array
function it2array(f, s, var)
	local t, var = {};
	while true do
		var = f(s, var);
	        if var == nil then break; end
		table.insert(t, var);
	end
	return t;
end

-- Treat the return of an iterator as key,value pairs, 
-- and build a table
function it2table(f, s, var)
	local t, var = {};
	while true do
		var, var2 = f(s, var);
	        if var == nil then break; end
		t[var] = var2;
	end
	return t;
end