Module: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 k, v in pairs(tbl) do		hash[v] = true end return hash 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

--[[useful for cargo queries. assumes that each element of tblToSort is itself a table, and sorts the parent table based on some value keyed by 'key' in each row

by default, if there is no 3rd argument specified, it returns the list in increasing order

specify true as a 3rd element to return elements in decreasing order instead ]] function p.sortByValueInRow(tblToSort, key, increasing) table.sort(tblToSort, function (a,b)			return (a[key] or 0) < (b[key] or 0) and not increasing		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

return p