diff --git a/lume.lua b/lume.lua index 73c2b33..191ef13 100644 --- a/lume.lua +++ b/lume.lua @@ -209,6 +209,19 @@ function lume.match(t, fn) 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) i = i and absindex(#t, i) or 1 j = j and absindex(#t, j) or #t diff --git a/test/test_lume.lua b/test/test_lume.lua index 57ac598..eb88a19 100644 --- a/test/test_lume.lua +++ b/test/test_lume.lua @@ -222,6 +222,15 @@ tests["lume.match"] = function() testeq( k, nil ) 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 tests["lume.slice"] = function() testeq( lume.slice({"a", "b", "c", "d", "e"}, 2, 4), {"b", "c", "d"} )