Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/lib/Bag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,24 @@ export default class Bag<T> {
this.dictionary.clear();
}

/**
* Returns true if both bags are subsets of each other.
* @return {boolean} true if this bag is equal to the other.
*/
equals(bag: Bag<T>): boolean {
// all elements in this are elements in bag
for (let element of this.dictionary.values()) {
if (this.count(element) !== bag.count(element)) {
return false;
}
}

// all elements in bag are elements in this
for (let element of bag.dictionary.values()) {
if (this.count(element) !== bag.count(element)) {
return false;
}
}
return true;
}
}// End of bag
23 changes: 23 additions & 0 deletions src/test/bagTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,4 +246,27 @@ describe('Bag',
});
expect(t).equals(1);
});

it('Non-empety bags with the same number of each element are equal',
function() {
let bag2 = new collections.Bag();
for (var i = 0; i < 5; i++) {
bag.add(i);
bag2.add(i);
}
expect(bag.equals(bag2)).equals(true);
});

it('Empty bags are equal',
function() {
let bag2 = new collections.Bag();
expect(bag.equals(bag2)).equals(true);
});

it('Bags with zero coppies of an element are equal to bags without the element',
function() {
let bag2 = new collections.Bag();
bag2.add(1, 0);
expect(bag.equals(bag2)).equals(true);
});
});