Skip to content

Commit

Permalink
Fixing MultiSet.remove
Browse files Browse the repository at this point in the history
Fix #197
  • Loading branch information
Yomguithereal committed Oct 4, 2022
1 parent 7b09731 commit 87a2d24
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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).
Expand Down
13 changes: 9 additions & 4 deletions multi-set.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
17 changes: 17 additions & 0 deletions test/multi-set.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down

0 comments on commit 87a2d24

Please sign in to comment.