mod_adhoc: Add support for commands only executable by global administrators
[prosody.git] / util / iterators.lua
index 08bb729c63f63a2331213c310dfc8026ee5beac6..dc692d64eac36e93a14b07c38488b56de10c5d44 100644 (file)
@@ -1,6 +1,6 @@
 -- Prosody IM
--- Copyright (C) 2008-2009 Matthew Wild
--- Copyright (C) 2008-2009 Waqas Hussain
+-- Copyright (C) 2008-2010 Matthew Wild
+-- Copyright (C) 2008-2010 Waqas Hussain
 -- 
 -- This project is MIT/X11 licensed. Please see the
 -- COPYING file in the source package for more information.
@@ -73,11 +73,53 @@ function count(f, s, var)
                var = ret[1];
                if var == nil then break; end
                x = x + 1;
-       end     
+       end
        
        return x;
 end
 
+-- Return the first n items an iterator returns
+function head(n, f, s, var)
+       local c = 0;
+       return function (s, var)
+               if c >= n then
+                       return nil;
+               end
+               c = c + 1;
+               return f(s, var);
+       end, s;
+end
+
+-- Skip the first n items an iterator returns
+function skip(n, f, s, var)
+       for i=1,n do
+               var = f(s, var);
+       end
+       return f, s, var;
+end
+
+-- Return the last n items an iterator returns
+function tail(n, f, s, var)
+       local results, count = {}, 0;
+       while true do
+               local ret = { f(s, var) };
+               var = ret[1];
+               if var == nil then break; end
+               results[(count%n)+1] = ret;
+               count = count + 1;
+       end
+
+       if n > count then n = count; end
+
+       local pos = 0;
+       return function ()
+               pos = pos + 1;
+               if pos > n then return nil; end
+               return unpack(results[((count-1+pos)%n)+1]);
+       end
+       --return reverse(head(n, reverse(f, s, var)));
+end
+
 -- Convert the values returned by an iterator to an array
 function it2array(f, s, var)
        local t, var = {};
@@ -89,7 +131,7 @@ function it2array(f, s, var)
        return t;
 end
 
--- Treat the return of an iterator as key,value pairs, 
+-- Treat the return of an iterator as key,value pairs,
 -- and build a table
 function it2table(f, s, var)
        local t, var = {};