count

function count( arr, fv ) --> res

Description

Sorts an array table into groups and returns a count for the number of objects in each group. Similar to group, but instead of returning a list of values, returns a count for the number of values in that group.

Parameters

arr

Array table where the values should be grouped.

fv

Function that takes a value from the array table and decides in which group it belongs.

Return Values

res

Table with count results.

Code

--ZFUNC-count-v1
local function count( tab, fv ) --> res
   local res = {}

   for i, v in pairs( tab ) do
      local k = fv( v )
      local base = res[ k ] or 0
      res[ k ] = base + 1
   end

   return res
end

return count

Examples

local t = require( "taptest" )
local count = require( "count" )
local iseven = require( "iseven" )

local res = count( { 1, 2, 3, 4, 5 }, function( v )
   if iseven( v ) then return "even" else return "odd" end
end )

t( res.even, 2 )
t( res.odd, 3 )

t()

Inspired by

See also