Diff

spec/util_iterators_spec.lua @ 9327:f6f1dec164b5

util.iterators: Add sorted_pairs() method
author Matthew Wild <mwild1@gmail.com>
date Fri, 21 Sep 2018 14:27:46 +0100
parent 8805:82d68951ec2a
child 9328:a9592107021b
line wrap: on
line diff
--- 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);