Skip to content

Commit

Permalink
improve hashset
Browse files Browse the repository at this point in the history
  • Loading branch information
waruqi committed Oct 6, 2024
1 parent 6c973f5 commit d329532
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 2 deletions.
17 changes: 17 additions & 0 deletions tests/modules/hashset/test.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import("core.base.hashset")

function test_hashset(t)
local h = hashset.of(1, 2, 3, 5, 5, 7, 1, 9, 4, 6, 8, 0)
t:require(h:size() == 10)
t:require_not(h:empty())
for item in h:items() do
t:require(h:has(item))
t:require_not(h:has(item + 10))
end
local prev = -1
for item in h:orderitems() do
t:require(item > prev)
prev = item
end
end

59 changes: 57 additions & 2 deletions xmake/core/base/hashset.lua
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,62 @@ function hashset_impl:to_array()
return result
end

-- iterate keys of hashtable
-- iterate items
--
-- @code
-- for item in instance:items() do
-- ...
-- end
-- @endcode
--
function hashset_impl:items()
return function (t, item)
local k, _ = next(t._DATA, item)
if k == hashset._NIL then
return nil
else
return k
end
end, self, nil
end

-- iterate order items
--
-- @code
-- for item in instance:orderitems() do
-- ...
-- end
-- @endcode
--
function hashset_impl:orderitems()
local orderkeys = table.orderkeys(self._DATA, function (a, b)
if a == hashset._NIL then
a = math.inf
end
if b == hashset._NIL then
b = math.inf
end
if type(a) == "table" then
a = tostring(a)
end
if type(b) == "table" then
b = tostring(b)
end
return a < b
end)
local i = 1
return function (t, k)
k = orderkeys[i]
i = i + 1
if k == hashset._NIL then
return nil
else
return k
end
end, self, nil
end

-- iterate keys (deprecated, please use items())
--
-- @code
-- for _, key in instance:keys() do
Expand All @@ -127,7 +182,7 @@ function hashset_impl:keys()
end, self, nil
end

-- order keys iterator
-- iterate order keys (deprecated, please use orderitems())
--
-- @code
-- for _, key in instance:orderkeys() do
Expand Down

0 comments on commit d329532

Please sign in to comment.