mirror of
https://github.com/bjc/prosody.git
synced 2025-04-03 21:27:38 +03:00
util.iterators: Add sorted_pairs() method
This commit is contained in:
parent
74cb650790
commit
5947c028a9
2 changed files with 43 additions and 0 deletions
|
@ -11,4 +11,34 @@ describe("util.iterators", function ()
|
|||
assert.same(output, expect);
|
||||
end);
|
||||
end);
|
||||
|
||||
describe("sorted_pairs", function ()
|
||||
it("should produce sorted pairs", function ()
|
||||
local orig = { b = 1, c = 2, a = "foo", d = false };
|
||||
local n, last_key = 0, nil;
|
||||
for k, v in iter.sorted_pairs(orig) do
|
||||
n = n + 1;
|
||||
if last_key then
|
||||
assert(k > last_key, "Expected "..k.." > "..last_key)
|
||||
end
|
||||
last_key = k;
|
||||
end
|
||||
assert.equal("d", last_key);
|
||||
assert.equal(4, n);
|
||||
end);
|
||||
|
||||
it("should allow a custom sort function", function ()
|
||||
local orig = { b = 1, c = 2, a = "foo", d = false };
|
||||
local n, last_key = 0, nil;
|
||||
for k, v in iter.sorted_pairs(orig, function (a, b) return a > b end) do
|
||||
n = n + 1;
|
||||
if last_key then
|
||||
assert(k < last_key, "Expected "..k.." > "..last_key)
|
||||
end
|
||||
last_key = k;
|
||||
end
|
||||
assert.equal("a", last_key);
|
||||
assert.equal(4, n);
|
||||
end);
|
||||
end);
|
||||
end);
|
||||
|
|
|
@ -177,6 +177,19 @@ function it.to_array(f, s, var)
|
|||
return t;
|
||||
end
|
||||
|
||||
function it.sorted_pairs(t, sort_func)
|
||||
local keys = it.to_array(it.keys(t));
|
||||
table.sort(keys, sort_func);
|
||||
local i = 0;
|
||||
return function ()
|
||||
i = i + 1;
|
||||
local key = keys[i];
|
||||
if key ~= nil then
|
||||
return key, t[key];
|
||||
end
|
||||
end;
|
||||
end
|
||||
|
||||
-- Treat the return of an iterator as key,value pairs,
|
||||
-- and build a table
|
||||
function it.to_table(f, s, var)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue