diff --git a/README.md b/README.md index 15bdf76..8fcd79b 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/lume.lua b/lume.lua index d9cd133..3a93f8c 100644 --- a/lume.lua +++ b/lume.lua @@ -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 diff --git a/test/test_lume.lua b/test/test_lume.lua index 4331e03..20a08f5 100644 --- a/test/test_lume.lua +++ b/test/test_lume.lua @@ -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({}), {} )