group

function group( arr, fv ) --> multiset

Description

Splits a array table into sub arrays, grouped by the result of running each value through fv.

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

multiset

A multiset with the detected groups.

Code

--ZFUNC-group-v1
local function group( arr, fv ) --> multiset
   local multiset = {}

   for i, v in ipairs( arr ) do
      local k = fv( v )
      if multiset[ k ] == nil then multiset[ k ] = {} end
      table.insert( multiset[ k ], v )
   end

   return multiset
end

return group

Examples

local t = require( "taptest" )
local group = require( "group" )
local iseven = require( "iseven" )
local same = require( "same" )

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

t( same( res.even, { 2, 4 } ), true )
t( same( res.odd, { 1, 3, 5 } ), true )

t()

Inspired by

See also