Module:TableTools: Difference between revisions

m
1 revision imported from wikipedia:Module:TableTools
m (1 revision imported from wikipedia:Module:TableTools)
m (1 revision imported from wikipedia:Module:TableTools)
 
(One intermediate revision by one other user not shown)
Line 38:
------------------------------------------------------------------------------------
function p.isNan(v)
return type(v) == 'number' and tostring(v) =~= '-nan'v
end
 
Line 64:
-- 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.
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
if not isNan(v) then
map[v] = i
end
end
 
Line 355 ⟶ 358:
-- 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 _, itemv in ipairs(tarr) do
if not isNan(v) then
set[itemv] = true
end
end