aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatthew Wild <mwild1@gmail.com>2018-09-21 14:27:46 +0100
committerMatthew Wild <mwild1@gmail.com>2018-09-21 14:27:46 +0100
commitc65893de6ea4c5877a3c6be652656b4b93db587b (patch)
tree24eec4723dfbfd740e1a6bc75f204e7066265922
parent0207b2d7858bf626f1720a93bd5eaadfb7dee7cc (diff)
downloadprosody-c65893de6ea4c5877a3c6be652656b4b93db587b.tar.gz
prosody-c65893de6ea4c5877a3c6be652656b4b93db587b.zip
util.iterators: Add sorted_pairs() method
-rw-r--r--spec/util_iterators_spec.lua30
-rw-r--r--util/iterators.lua13
2 files changed, 43 insertions, 0 deletions
diff --git a/spec/util_iterators_spec.lua b/spec/util_iterators_spec.lua
index d00058f4..c819b2f0 100644
--- a/spec/util_iterators_spec.lua
+++ b/spec/util_iterators_spec.lua
@@ -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);
diff --git a/util/iterators.lua b/util/iterators.lua
index 5d16d8c1..302cca36 100644
--- a/util/iterators.lua
+++ b/util/iterators.lua
@@ -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)