Added lume.sort(), updated tests & README

This commit is contained in:
rxi 2015-01-10 16:54:23 +00:00
parent b873c043c5
commit 7a0f5a0831
3 changed files with 37 additions and 0 deletions

View File

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

View File

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

View File

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