diff --git a/src/lib/Bag.ts b/src/lib/Bag.ts index e3f0c32..a1e32ad 100644 --- a/src/lib/Bag.ts +++ b/src/lib/Bag.ts @@ -191,4 +191,24 @@ export default class Bag { 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): 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 diff --git a/src/test/bagTest.ts b/src/test/bagTest.ts index 8770e6b..52e78a1 100644 --- a/src/test/bagTest.ts +++ b/src/test/bagTest.ts @@ -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); + }); });