Module talk:TableTools: Difference between revisions
←Created page with '== removeDuplicate does not remove duplicate NaN == <source lang="lua"> function p.removeDuplicates(t) checkType('removeDuplicates', 1, t, 'table') local isNan...' |
|||
| Line 23: | Line 23: | ||
function p.removeDuplicates(t) | function p.removeDuplicates(t) | ||
checkType('removeDuplicates', 1, t, 'table') | checkType('removeDuplicates', 1, t, 'table') | ||
local isNan | local ret, isNan, exists, hasNan = {}, p.isNan, {}, nil | ||
for _, v in ipairs(t) do | |||
for | |||
if isNan(v) then | if isNan(v) then | ||
-- NaNs can't be table keys in exists[], and they are also equal to each other in Lua. | -- NaNs can't be table keys in exists[], and they are also equal to each other in Lua. | ||
-- But we want only one Nan in ret[], and there may be multiple Nan's in t[]. | -- But we want only one Nan in ret[], and there may be multiple Nan's in t[]. | ||
if not hasNan then | if not hasNan then | ||
hasNan = true | |||
ret[#ret + 1] = v | ret[#ret + 1] = v | ||
end | end | ||
else | else | ||
if not exists[v] then | if not exists[v] then | ||
exists[v] = true | |||
ret[#ret + 1] = v | ret[#ret + 1] = v | ||
end | end | ||
end | end | ||
Revision as of 07:53, 2 February 2014
removeDuplicate does not remove duplicate NaN
<source lang="lua"> function p.removeDuplicates(t) checkType('removeDuplicates', 1, t, 'table') local isNan = p.isNan local ret, exists = {}, {} for i, v in ipairs(t) do if isNan(v) then -- NaNs can't be table keys, and they are also unique, so we don't need to check existence. ret[#ret + 1] = v else if not exists[v] then ret[#ret + 1] = v exists[v] = true end end end return ret end </source> This should be: <source lang="lua"> function p.removeDuplicates(t) checkType('removeDuplicates', 1, t, 'table') local ret, isNan, exists, hasNan = {}, p.isNan, {}, nil for _, v in ipairs(t) do if isNan(v) then -- NaNs can't be table keys in exists[], and they are also equal to each other in Lua. -- But we want only one Nan in ret[], and there may be multiple Nan's in t[]. if not hasNan then hasNan = true ret[#ret + 1] = v end else if not exists[v] then exists[v] = true ret[#ret + 1] = v end end end return ret end </source> -- verdy_p (talk) 07:50, 2 February 2014 (UTC)