Module:TableTools: Difference between revisions

add key/value pair union function
Enwikipedia>Mr. Stradivarius
(fix lim variable in intersection function)
Enwikipedia>Mr. Stradivarius
(add key/value pair union function)
Line 39:
------------------------------------------------------------------------------------
-- union
--
-- This returns the union of the key/value pairs of n tables. If any of the tables
-- contain different values for the same table key, the table value is converted
-- to an array holding all of the different values.
------------------------------------------------------------------------------------
--]]
function p.union(...)
local ret, trackArrays = {}, {}
for i = 1, select('#', ...) do
local t = select(i, ...)
for k, v in pairs(t) do
local retKey = ret[k]
if retKey == nil then
ret[k] = v
elseif retKey ~= v then
if trackArrays[k] then
local array = ret[k]
array[#array + 1] = v
ret[k] = array
else
ret[k] = {ret[k], v}
trackArrays[k] = true
end
end
end
end
return ret
end
 
--[[
------------------------------------------------------------------------------------
-- valueUnion
--
-- This returns the union of the values of n tables, as an array. For example, for
Line 45 ⟶ 77:
------------------------------------------------------------------------------------
--]]
function p.unionvalueUnion(...)
local vals, ret = {}, {}
for i = 1, select('#', ...) do
Line 70 ⟶ 102:
------------------------------------------------------------------------------------
-- intersection
--
-- This returns the intersection of the key/value pairs of n tables. Both the key
-- and the value must match to be included in the resulting table.
------------------------------------------------------------------------------------
--]]
 
--[[
------------------------------------------------------------------------------------
-- valueIntersection
--
-- This returns the intersection of the values of n tables, as an array. For
Line 76 ⟶ 117:
------------------------------------------------------------------------------------
--]]
function p.intersectionvalueIntersection(...)
local vals, ret = {}, {}
local lim = select('#', ...)