From 199b8ded1d752c5f6b29619eaf3843eca9c760ea Mon Sep 17 00:00:00 2001 From: jalhund Date: Wed, 18 May 2022 05:17:31 +0000 Subject: [PATCH] tablex: Add spairs (alternative of pairs that returns sorted table) --- .test/tests.lua | 36 ++++++++++++++++++++++++++++++++++++ tablex.lua | 24 ++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/.test/tests.lua b/.test/tests.lua index 260dda1..a8cd0c3 100644 --- a/.test/tests.lua +++ b/.test/tests.lua @@ -116,3 +116,39 @@ local function test_deep_equal() assert(not tablex.deep_equal(y, x)) end +local function test_spairs() + local t = { + player1 = { + name = "Joe", + score = 8 + }, + player2 = { + name = "Robert", + score = 7 + }, + player3 = { + name = "John", + score = 10 + } + } + + local sorted_names = {} + local sorted_score = {} + + for k, v in tablex.spairs(t, function(t, a, b) + return t[a].score > t[b].score + end) do + tablex.push(sorted_names, v.name) + tablex.push(sorted_score, v.score) + end + + assert(tablex.deep_equal(sorted_names, + { + "John", "Joe", "Robert" + })) + + assert(tablex.deep_equal(sorted_score, + { + 10, 8, 7 + })) +end \ No newline at end of file diff --git a/tablex.lua b/tablex.lua index 72cd437..8624dfb 100644 --- a/tablex.lua +++ b/tablex.lua @@ -537,4 +537,28 @@ function tablex.ripairs(t) return _ripairs_iter, t, #t + 1 end +-- works like pairs, but returns sorted table +function tablex.spairs(t, fn) + local keys = {} + for k in pairs(t) do + tablex.push(keys, k) + end + + if fn then + table.sort(keys, function(a,b) return fn(t, a, b) end) + else + -- sort by keys if no function passed + table.sort(keys) + end + + local i = 0 + return function() + i = i + 1 + if keys[i] then + return keys[i], t[keys[i]] + end + end +end + + return tablex