Added lume.count() function and tests

This commit is contained in:
rxi 2014-04-05 12:11:13 +01:00
parent 3a4ce4fe3b
commit fdf01937e2
2 changed files with 22 additions and 0 deletions

View File

@ -209,6 +209,19 @@ function lume.match(t, fn)
end end
function lume.count(t, fn)
local count = 0
if fn then
for k, v in pairs(t) do
if fn(v) then count = count + 1 end
end
else
for k in pairs(t) do count = count + 1 end
end
return count
end
function lume.slice(t, i, j) function lume.slice(t, i, j)
i = i and absindex(#t, i) or 1 i = i and absindex(#t, i) or 1
j = j and absindex(#t, j) or #t j = j and absindex(#t, j) or #t

View File

@ -222,6 +222,15 @@ tests["lume.match"] = function()
testeq( k, nil ) testeq( k, nil )
end end
-- lume.count
tests["lume.count"] = function()
local t = { a = 1, b = 2, c = 5, [13] = 22, z = 8 }
testeq( lume.count(t), 5 )
testeq( lume.count(t, function(x) return x % 2 == 0 end ), 3 )
local a = { 5, 6, 7, 8, 9 }
testeq( lume.count(a), #a )
end
-- lume.slice -- lume.slice
tests["lume.slice"] = function() tests["lume.slice"] = function()
testeq( lume.slice({"a", "b", "c", "d", "e"}, 2, 4), {"b", "c", "d"} ) testeq( lume.slice({"a", "b", "c", "d", "e"}, 2, 4), {"b", "c", "d"} )