diff --git a/packages/collection/__tests__/collection.test.ts b/packages/collection/__tests__/collection.test.ts index b2d01213f..73d3adaf1 100644 --- a/packages/collection/__tests__/collection.test.ts +++ b/packages/collection/__tests__/collection.test.ts @@ -3,17 +3,17 @@ import { describe, test, expect } from 'vitest'; import { Collection } from '../src/index.js'; -type TestCollection = Collection; +type TestCollection = Collection; -function createCollection(): TestCollection { +function createCollection(): TestCollection { return new Collection(); } -function createCollectionFrom(...entries: [key: string, value: number][]): TestCollection { +function createCollectionFrom(...entries: [key: string, value: V][]): TestCollection { return new Collection(entries); } -function createTestCollection(): TestCollection { +function createTestCollection(): TestCollection { return createCollectionFrom(['a', 1], ['b', 2], ['c', 3]); } @@ -770,6 +770,19 @@ describe('sort() tests', () => { }); }); +describe('subtract() tests', () => { + const coll1 = createCollectionFrom(['a', 1], ['b', 2], ['c', 3], ['d', undefined]); + const coll2 = createCollectionFrom(['b', 2], ['c', 0]); + + test('it returns a new collection', () => { + const c = coll1.subtract(coll2); + expect(c).toBeInstanceOf(Collection); + expect(c.size).toStrictEqual(3); + + expect(c).toStrictEqual(createCollectionFrom(['a', 1], ['c', 3], ['d', undefined])); + }); +}); + describe('sweep() test', () => { const coll = createTestCollection(); diff --git a/packages/collection/src/collection.ts b/packages/collection/src/collection.ts index c8a14cdea..425fcd0fa 100644 --- a/packages/collection/src/collection.ts +++ b/packages/collection/src/collection.ts @@ -684,6 +684,22 @@ export class Collection extends Map { return coll; } + /** + * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other. + * + * @param other - The other Collection to filter against + */ + public subtract(other: ReadonlyCollection): Collection { + const coll = new this.constructor[Symbol.species](); + for (const [k, v] of this) { + if (!other.has(k) || !Object.is(v, other.get(k))) { + coll.set(k, v); + } + } + + return coll; + } + /** * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other. *