From 71ae0ff1f713e45430ea02a1ff1e46ab2d28b63c Mon Sep 17 00:00:00 2001 From: Aki Date: Fri, 2 Aug 2024 23:08:06 +0200 Subject: Multiset ref counter will no longer go into negative numbers --- headers/multiset.lua | 10 +++++++--- 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) -- cgit v1.1