# HG changeset patch # User Matthew Wild # Date 1537536466 -3600 # Node ID f6f1dec164b5d2484af393ccc062179be4f2be33 # Parent c9c4b8bc53b17af932f3a55a6e9c37c9143ae165 util.iterators: Add sorted_pairs() method diff -r c9c4b8bc53b1 -r f6f1dec164b5 spec/util_iterators_spec.lua --- a/spec/util_iterators_spec.lua Mon Sep 17 15:28:53 2018 +0100 +++ b/spec/util_iterators_spec.lua Fri Sep 21 14:27:46 2018 +0100 @@ -11,4 +11,34 @@ 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 -r c9c4b8bc53b1 -r f6f1dec164b5 util/iterators.lua --- a/util/iterators.lua Mon Sep 17 15:28:53 2018 +0100 +++ b/util/iterators.lua Fri Sep 21 14:27:46 2018 +0100 @@ -177,6 +177,19 @@ 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)