From c65893de6ea4c5877a3c6be652656b4b93db587b Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Fri, 21 Sep 2018 14:27:46 +0100 Subject: util.iterators: Add sorted_pairs() method --- spec/util_iterators_spec.lua | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'spec') 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); -- cgit v1.2.3