tablex: Add spairs (alternative of pairs that returns sorted table)

This commit is contained in:
jalhund 2022-05-18 05:17:31 +00:00
parent be48dd9115
commit 199b8ded1d
2 changed files with 60 additions and 0 deletions

View File

@ -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

View File

@ -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