Added lume.first() and .last(), updated README.md and tests

This commit is contained in:
rxi 2014-12-12 21:33:41 +00:00
parent de37bd6d65
commit 8f1267f967
3 changed files with 42 additions and 0 deletions

View File

@ -178,6 +178,20 @@ than a string. Creates and returns a new array of the given slice.
lume.slice({"a", "b", "c", "d", "e"}, 2, 4) -- Returns {"b", "c", "d"}
```
### lume.first(t [, n])
Returns the first element of an array or nil if the array is empty. If `n` is
specificed an array of the first `n` elements is returned.
```lua
lume.first({"a", "b", "c"}) -- Returns "a"
```
### lume.last(t [, n])
Returns the last element of an array or nil if the array is empty. If `n` is
specificed an array of the last `n` elements is returned.
```lua
lume.last({"a", "b", "c"}) -- Returns "c"
```
### lume.invert(t)
Returns a copy of the table where the keys have become the values and the
values the keys.

View File

@ -257,6 +257,18 @@ function lume.slice(t, i, j)
end
function lume.first(t, n)
if not n then return t[1] end
return lume.slice(t, 1, n)
end
function lume.last(t, n)
if not n then return t[#t] end
return lume.slice(t, -n, -1)
end
function lume.invert(t)
local rtn = {}
for k, v in pairs(t) do rtn[v] = k end

View File

@ -266,6 +266,22 @@ tests["lume.slice"] = function()
testeq( lume.slice({"a", "b", "c", "d", "e"}, -3, 900), {"c", "d", "e"} )
end
-- lume.first
tests["lume.first"] = function()
local t = { "a", "b", "c", "d", "e" }
testeq( lume.first(t), "a" )
testeq( lume.first(t, 1), { "a" } )
testeq( lume.first(t, 2), { "a", "b" } )
end
-- lume.last
tests["lume.last"] = function()
local t = { "a", "b", "c", "d", "e" }
testeq( lume.last(t), "e" )
testeq( lume.last(t, 1), { "e" } )
testeq( lume.last(t, 2), { "d", "e" } )
end
-- lume.invert
tests["lume.invert"] = function()
testeq( lume.invert({}), {} )