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( "tapered" )
local group = require( "group" )

local iseven = require( "iseven" )

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

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

t.done()

Inspired by

See also