diff options
author | Clement Farabet <clement.farabet@gmail.com> | 2012-10-31 23:58:19 +0400 |
---|---|---|
committer | Clement Farabet <clement.farabet@gmail.com> | 2012-10-31 23:58:19 +0400 |
commit | c6e95bb3fa4a38b6d739d37c589d9a98c77cad94 (patch) | |
tree | 2c4c529dfa7d4c2d3275a511912d1ad7ff45abb9 /init.lua | |
parent | 0369f078ad46b83aa7a8823ea6a4f76b0b9a39a3 (diff) |
Better prune.
Diffstat (limited to 'init.lua')
-rw-r--r-- | init.lua | 23 |
1 files changed, 19 insertions, 4 deletions
@@ -618,14 +618,29 @@ end -------------------------------------------------------------------------------- -- prune: remove duplicates from a table +-- if a hash function is provided, it is used to produce a unique hash for each +-- element in the input table. +-- if a merge function is provided, it defines how duplicate entries are merged, +-- otherwise, a random entry is picked. -------------------------------------------------------------------------------- -function table.prune(tbl) +function table.prune(tbl, hashfunc, merge) local hashes = {} - for i,v in ipairs(tbl) do - hashes[v] = true + local hash = hashfunc or function(a) return a end + if merge then + for i,v in ipairs(tbl) do + if not hashes[hash(v)] then + hashes[hash(v)] = v + else + hashes[hash(v)] = merge(v, hashes[hash(v)]) + end + end + else + for i,v in ipairs(tbl) do + hashes[hash(v)] = v + end end local ntbl = {} - for v in pairs(hashes) do + for _,v in pairs(hashes) do table.insert(ntbl, v) end return ntbl |