Module:TableTools: Difference between revisions

m
2 revisions imported from wikipedia:Module:TableTools: All aboard the import train again. Originally imported from English Wikipedia.
(updates/fixes requested by User:Uzume)
m (2 revisions imported from wikipedia:Module:TableTools: All aboard the import train again. Originally imported from English Wikipedia.)
 
Line 38:
------------------------------------------------------------------------------------
function p.isNan(v)
return type(v) == 'number' and tostring(v) ~== v'-nan'
end
 
Line 64:
-- removed, but otherwise the array order is unchanged.
------------------------------------------------------------------------------------
function p.removeDuplicates(arrt)
checkType('removeDuplicates', 1, arrt, 'table')
local isNan = p.isNan
local ret, exists = {}, {}
for _, v in ipairs(arrt) do
if isNan(v) then
-- NaNs can't be table keys, and they are also unique, so we don't need to check existence.
Line 337:
--
-- 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
map[v] = i
if not isNan(v) then
map[v] = i
end
end
 
Line 358 ⟶ 355:
-- 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(arrt)
checkType("listToSet", 1, arrt, "table")
 
local isNan = p.isNan
local set = {}
for _, vitem in ipairs(arrt) do
set[vitem] = true
if not isNan(v) then
set[v] = true
end
end