From db25f529b26d7c819c1c42ad3e26c2263ea2da0e Mon Sep 17 00:00:00 2001 From: Suneet Tipirneni <77477100+suneettipirneni@users.noreply.github.com> Date: Tue, 11 Jan 2022 06:30:16 -0500 Subject: [PATCH] types: add `ReadonlyCollection` (#7245) Co-authored-by: Vlad Frangu --- packages/collection/src/index.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/collection/src/index.ts b/packages/collection/src/index.ts index 8fd02b2fb..c0180a20f 100644 --- a/packages/collection/src/index.ts +++ b/packages/collection/src/index.ts @@ -9,6 +9,12 @@ export interface CollectionConstructor { readonly [Symbol.species]: CollectionConstructor; } +/** + * Represents an immutable version of a collection + */ +export type ReadonlyCollection = ReadonlyMap & + Omit, 'forEach' | 'ensure' | 'reverse' | 'sweep' | 'sort' | 'get' | 'set' | 'delete'>; + /** * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself * @@ -562,7 +568,7 @@ export class Collection extends Map { * @example * const newColl = someColl.clone(); */ - public clone() { + public clone(): Collection { return new this.constructor[Symbol.species](this); } @@ -574,7 +580,7 @@ export class Collection extends Map { * @example * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); */ - public concat(...collections: Collection[]) { + public concat(...collections: ReadonlyCollection[]) { const newColl = this.clone(); for (const coll of collections) { for (const [key, val] of coll) newColl.set(key, val); @@ -591,7 +597,7 @@ export class Collection extends Map { * * @returns Whether the collections have identical contents */ - public equals(collection: Collection) { + public equals(collection: ReadonlyCollection) { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!collection) return false; // runtime check if (this === collection) return true; @@ -634,7 +640,7 @@ export class Collection extends Map { * * @param other The other Collection to filter against */ - public intersect(other: Collection): Collection { + public intersect(other: ReadonlyCollection): Collection { const coll = new this.constructor[Symbol.species](); for (const [k, v] of other) { if (this.has(k) && Object.is(v, this.get(k))) { @@ -649,7 +655,7 @@ export class Collection extends Map { * * @param other The other Collection to filter against */ - public difference(other: Collection): Collection { + public difference(other: ReadonlyCollection): Collection { const coll = new this.constructor[Symbol.species](); for (const [k, v] of other) { if (!this.has(k)) coll.set(k, v);