Skip to content

Commit

Permalink
feat(collection): use @@species in static methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Renegade334 committed Jan 21, 2025
1 parent aa90f00 commit 7775ea8
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions packages/collection/src/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ export type ReadonlyCollection<Key, Value> = Omit<

export interface Collection<Key, Value> {
/**
* Ambient declaration to allow `this.constructor[@@species]` in class methods.
* Ambient declaration to allow references to `this.constructor` in class methods.
*
* @internal
*/
constructor: typeof Collection & { readonly [Symbol.species]: typeof Collection };
constructor: typeof Collection;
}

/**
Expand All @@ -26,6 +26,11 @@ export interface Collection<Key, Value> {
* @typeParam Value - The value type this collection holds
*/
export class Collection<Key, Value> extends Map<Key, Value> {
/**
* @internal
*/
declare public static readonly [Symbol.species]: typeof Collection;

/**
* Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.
*
Expand Down Expand Up @@ -1076,7 +1081,7 @@ export class Collection<Key, Value> extends Map<Key, Value> {
entries: Iterable<[Key, Value]>,
combine: (firstValue: Value, secondValue: Value, key: Key) => Value,
): Collection<Key, Value> {
const coll = new Collection<Key, Value>();
const coll = new this[Symbol.species]<Key, Value>();
for (const [key, value] of entries) {
if (coll.has(key)) {
coll.set(key, combine(coll.get(key)!, value, key));
Expand Down

0 comments on commit 7775ea8

Please sign in to comment.