From 87a2d2452cf855076aef5a5036cac7d545cc446b Mon Sep 17 00:00:00 2001 From: Yomguithereal Date: Tue, 4 Oct 2022 16:51:40 +0200 Subject: [PATCH] Fixing MultiSet.remove Fix #197 --- CHANGELOG.md | 4 ++++ multi-set.js | 13 +++++++++---- test/multi-set.js | 17 +++++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 95d47fcc..40e74e6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.39.3 (provisional) + +* Fixing `NaN` size issue with `MultiSet.remove` when removing non-existent keys. + ## 0.39.2 * Fixing typings of low-level structure consuming methods (@jerome-benoit). diff --git a/multi-set.js b/multi-set.js index 3206af73..847c01dc 100644 --- a/multi-set.js +++ b/multi-set.js @@ -175,15 +175,20 @@ MultiSet.prototype.remove = function(item, count) { if (typeof count !== 'number') throw new Error('mnemonist/multi-set.remove: given count should be a number.'); - var currentCount = this.multiplicity(item), - newCount = Math.max(0, currentCount - count); + var currentCount = this.items.get(item); + + if (typeof currentCount === 'undefined') return; + + var newCount = Math.max(0, currentCount - count); if (newCount === 0) { - this.delete(item); + this.items.delete(item); + this.size -= currentCount; + this.dimension--; } else { this.items.set(item, newCount); - this.size -= (currentCount - newCount); + this.size -= count; } return; diff --git a/test/multi-set.js b/test/multi-set.js index 4a17fe93..3c150d4f 100644 --- a/test/multi-set.js +++ b/test/multi-set.js @@ -311,6 +311,23 @@ describe('MultiSet', function() { assert.deepStrictEqual(top, [['i', 7]]); }); + it('size should remain consistent (issue #197).', function() { + var set = new MultiSet(); + + set.add('one'); + set.add('one'); + set.remove('one'); + set.remove('one'); + + assert.strictEqual(set.size, 0); + assert.strictEqual(set.dimension, 0); + + set.remove('one'); + + assert.strictEqual(set.size, 0); + assert.strictEqual(set.dimension, 0); + }); + describe('helpers', function() { it('#.isSuperset', function() {