diff --git a/README.md b/README.md index df7c923..05cda7f 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,16 @@ lume.weightedchoice({ ["cat"] = 10, ["dog"] = 5, ["frog"] = 0 }) ### lume.shuffle(t) Returns a shuffled copy of the array `t`. +### lume.sort(t [, comp]) +Returns a copy of the array `t` with all its items sorted. If `comp` is a +function it will be used to compare the items when sorting. If `comp` is a +string the it will be used as the key to sort the items by. +```lua +lume.sort({ 1, 4, 3, 2, 5 }) -- Returns { 1, 2, 3, 4, 5 } +lume.sort({ {z=2}, {z=3}, {z=1} }, "z") -- Returns { {z=1}, {z=2}, {z=3} } +lume.sort({ 1, 3, 2 }, function(a, b) return a > b end) -- Returns { 3, 2, 1 } +``` + ### lume.array(...) Iterates the supplied iterator and returns an array filled with the values. ```lua diff --git a/lume.lua b/lume.lua index c1c557a..38ae4e3 100644 --- a/lume.lua +++ b/lume.lua @@ -158,6 +158,21 @@ function lume.shuffle(t) end +function lume.sort(t, comp) + local rtn = lume.clone(t) + if comp then + if type(comp) == "string" then + table.sort(rtn, function(a, b) return a[comp] < b[comp] end) + else + table.sort(rtn, comp) + end + else + table.sort(rtn) + end + return rtn +end + + function lume.array(...) local t = {} for x in ... do t[#t + 1] = x end diff --git a/test/test_lume.lua b/test/test_lume.lua index 7979dbe..8f07ffb 100644 --- a/test/test_lume.lua +++ b/test/test_lume.lua @@ -115,6 +115,18 @@ tests["lume.shuffle"] = function() testeq( lume.shuffle({}), {} ) end +-- lume.sort +tests["lume.sort"] = function() + local t = { 1, 5, 2, 4, 3 } + local fn = function(a, b) return a > b end + testeq( t == lume.sort(t), false ) + testeq( lume.sort(t), { 1, 2, 3, 4, 5 } ) + testeq( lume.sort(t, fn), { 5, 4, 3, 2, 1 } ) + testeq( t, { 1, 5, 2, 4, 3 } ) + local t = { { id = 2 }, { id = 3 }, { id = 1 } } + testeq( lume.sort(t, "id"), { { id = 1 }, { id = 2 }, { id = 3 } }) +end + -- lume.array tests["lume.array"] = function() local t = lume.array(pairs({a=0, b=0, c=0}))