Skip to content

Commit db25f52

Browse files
types: add ReadonlyCollection (#7245)
Co-authored-by: Vlad Frangu <[email protected]>
1 parent 16938da commit db25f52

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

Diff for: packages/collection/src/index.ts

+11-5
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@ export interface CollectionConstructor {
99
readonly [Symbol.species]: CollectionConstructor;
1010
}
1111

12+
/**
13+
* Represents an immutable version of a collection
14+
*/
15+
export type ReadonlyCollection<K, V> = ReadonlyMap<K, V> &
16+
Omit<Collection<K, V>, 'forEach' | 'ensure' | 'reverse' | 'sweep' | 'sort' | 'get' | 'set' | 'delete'>;
17+
1218
/**
1319
* Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself
1420
*
@@ -562,7 +568,7 @@ export class Collection<K, V> extends Map<K, V> {
562568
* @example
563569
* const newColl = someColl.clone();
564570
*/
565-
public clone() {
571+
public clone(): Collection<K, V> {
566572
return new this.constructor[Symbol.species](this);
567573
}
568574

@@ -574,7 +580,7 @@ export class Collection<K, V> extends Map<K, V> {
574580
* @example
575581
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
576582
*/
577-
public concat(...collections: Collection<K, V>[]) {
583+
public concat(...collections: ReadonlyCollection<K, V>[]) {
578584
const newColl = this.clone();
579585
for (const coll of collections) {
580586
for (const [key, val] of coll) newColl.set(key, val);
@@ -591,7 +597,7 @@ export class Collection<K, V> extends Map<K, V> {
591597
*
592598
* @returns Whether the collections have identical contents
593599
*/
594-
public equals(collection: Collection<K, V>) {
600+
public equals(collection: ReadonlyCollection<K, V>) {
595601
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
596602
if (!collection) return false; // runtime check
597603
if (this === collection) return true;
@@ -634,7 +640,7 @@ export class Collection<K, V> extends Map<K, V> {
634640
*
635641
* @param other The other Collection to filter against
636642
*/
637-
public intersect<T>(other: Collection<K, T>): Collection<K, T> {
643+
public intersect<T>(other: ReadonlyCollection<K, T>): Collection<K, T> {
638644
const coll = new this.constructor[Symbol.species]<K, T>();
639645
for (const [k, v] of other) {
640646
if (this.has(k) && Object.is(v, this.get(k))) {
@@ -649,7 +655,7 @@ export class Collection<K, V> extends Map<K, V> {
649655
*
650656
* @param other The other Collection to filter against
651657
*/
652-
public difference<T>(other: Collection<K, T>): Collection<K, V | T> {
658+
public difference<T>(other: ReadonlyCollection<K, T>): Collection<K, V | T> {
653659
const coll = new this.constructor[Symbol.species]<K, V | T>();
654660
for (const [k, v] of other) {
655661
if (!this.has(k)) coll.set(k, v);

0 commit comments

Comments
 (0)