Module:TableUtil

-- TableUtil local p = {}

function p.keyOf(tbl, val) for k, v in pairs(tbl) do		if v == val then return k		end end return nil end

function p.hash(tbl) local hash = {} for _, v in pairs(tbl) do		hash[v] = true end return hash end

function p.appendHash(tbl, parent) for _, v in pairs(tbl) do		parent[v] = true end return end

-- sorts tblToSort to be in the same order as the elements appear in lookup function p.sortByKeyOrder(tblToSort,lookup) table.sort(tblToSort, function (a,b)			return (p.keyOf(lookup,a) or 0) < (p.keyOf(lookup,b) or 0)		end	) return end

function p.mergeArrays(tbl1,tbl2) -- tbl1 is modified to include the elements of tbl2 appended to the end. Order is preserved. for _, v in ipairs(tbl2) do		tbl1[#tbl1+1] = v	end return end

-- table.remove for non-integer key function p.remove(tbl, key) local output = tbl[key] tbl[key] = nil return output end

-- returns a copy of tbl with the elements in opposite order (not a deep copy) function p.reverse(tbl) local tbl2 = {} local len = #tbl for i = len, 1, -1 do		tbl2[len - i + 1] = tbl[i] end return tbl2 end

function p.slice(tbl, s, e)	local tbl2 = {} for k = s, e do		tbl2[#tbl2+1] = tbl[k] end return tbl2 end

function p.printList(tbl) if #tbl == 1 then return tbl[1] elseif #tbl == 2 then return table.concat(tbl, ' and ') else last = table.remove(tbl, #tbl) list = table.concat(tbl, ', ') return list .. ', and ' .. (last or '') end end

return p