Looking for a solution to extending a base class Collection
in JavaScript/TypeScript to handle domain-specific use cases by implementing a "destructing" method like filter
that returns a new instance with filtered elements. In PHP, you can achieve this using return new self()
, but struggling to find an equivalent solution in JS/TS.
The current workaround involves overwriting the newInstance
method in all child classes. Is there a more elegant solution to this issue?
class Collection<E> {
protected items: E[];
constructor(items: any[] = []) {
this.items = items;
}
// struggling to create a new instance
protected newInstance(items: E[]) {
return new Collection(items);
}
size() {
return this.items.length;
}
// filter and return new instance
filter(callback: (item: any, index?: number) => boolean): this {
return this.newInstance(this.items.filter(callback)) as this;
}
}
class NumberCollection extends Collection<number> {
sum() {
return this.items.reduce((a, b) => a + b, 0);
}
}
let numbers = new NumberCollection([1, 2, 3, 4]);
console.log(numbers.sum());
console.log(numbers.filter((n) => n > 1).sum());