Open main menu

Changes

Module:TableTools

328 bytes added, 13:08, 31 January 2022
updates/fixes requested by User:Uzume
------------------------------------------------------------------------------------
function p.isNan(v)
return type(v) == 'number' and tostring(v) ~== '-nan'v
end
-- removed, but otherwise the array order is unchanged.
------------------------------------------------------------------------------------
function p.removeDuplicates(tarr) checkType('removeDuplicates', 1, tarr, 'table')
local isNan = p.isNan
local ret, exists = {}, {}
for _, v in ipairs(tarr) do
if isNan(v) then
-- NaNs can't be table keys, and they are also unique, so we don't need to check existence.
--
-- Transposes the keys and values in an array. For example, {"a", "b", "c"} ->
-- {a = 1, b = 2, c = 3}. Duplicates are not supported (result values refer to-- the index of the last duplicate) and NaN values are ignored.
------------------------------------------------------------------------------------
function p.invert(arr)
checkType("invert", 1, arr, "table")
local isNan = p.isNan
local map = {}
for i, v in ipairs(arr) do
if not isNan(v) then map[v] = i end
end
-- Creates a set from the array part of the table. Indexing the set by any of the
-- values of the array returns true. For example, {"a", "b", "c"} ->
-- {a = true, b = true, c = true}. NaN values are ignored as Lua considers them-- never equal to any value (including other NaNs or even themselves).
------------------------------------------------------------------------------------
function p.listToSet(tarr) checkType("listToSet", 1, tarr, "table") local isNan = p.isNan
local set = {}
for _, item v in ipairs(tarr) do if not isNan(v) then set[itemv] = true end
end
Anonymous user