invertby

function invertby( tab [, fv] ) --> itab

Description

Creates a table composed of the inverted keys and values of tab. The inverted table is generated from the results of running each value of tab thru fv. The corresponding inverted value of each inverted key is an array table of keys responsible for generating the inverted value.

Parameters

tab

The table that should be inverted.

fv

Function that defines the key by the value. By default is the value the key.

Return Values

itab

Inverted version of tab.

Code

--ZFUNC-invertby-v1
local function invertby( tab, fv ) --> itab
   local itab = {}
   for k, v in pairs( tab ) do
      local ik = v
      if fv then ik = fv( v ) end
      itab[ ik ] = itab[ ik ] or {}
      table.insert( itab[ ik ], k )
   end
   return itab
end

return invertby

Examples

local t = require( "tapered" )
local invertby = require( "invertby" )
-- util functions
local like = require( "like" )

-- https://lodash.com/docs#invertBy
local tab = { a=1, b=2, c=1 }
local itab = invertby( tab )
t.ok( like( itab[ 1 ], { "a", "c" } ) )
t.ok( like( itab[ 2 ], { "b" } ) )

itab = invertby( tab, function( v ) return 'g'..v end )
t.ok( like( itab.g1, { "a", "c" } ) )
t.ok( like( itab.g2, { "b" } ) )

t.done()

Inspired by