diff options
-rw-r--r-- | headers/multiset.lua | 10 | ||||
-rw-r--r-- | spec/multiset_spec.lua | 7 |
2 files changed, 14 insertions, 3 deletions
diff --git a/headers/multiset.lua b/headers/multiset.lua index 7fb1a49..be55e7b 100644 --- a/headers/multiset.lua +++ b/headers/multiset.lua @@ -6,7 +6,7 @@ --- a:remove"value" --> a:has"value" == true --- a:remove"value" --> a:has"value" == false --- a:remove"value" --> a:has"value" == false ---- a:add"value" --> a:has"value" == false +--- a:add"value" --> a:has"value" == true local tablex = require "pl.tablex" local multiset = {} @@ -31,9 +31,13 @@ function multiset:add (value) end ---- Reduce reference count for *value*. May go into negative values. +--- Reduce reference count for *value*. It will not go into negative numbers and it will not mutate state if the key +--- was not part of the set. function multiset:remove (value) - self.counts[value] = (self.counts[value] or 0) - 1 + local current = (self.counts[value] or 0) + if current > 0 then + self.counts[value] = current - 1 + end end diff --git a/spec/multiset_spec.lua b/spec/multiset_spec.lua index 7639066..abdeb94 100644 --- a/spec/multiset_spec.lua +++ b/spec/multiset_spec.lua @@ -95,6 +95,13 @@ describe("Values", function() it("are not counted after removal", function() assert.are.equal(1, #set) end) + + it("are removed only once", function() + set:remove"will-be-removed" + assert.is_false(set:has"will-be-removed") + set:add"will-be-removed" + assert.is_true(set:has"will-be-removed") + end) end) |