howardlo
howardlo

Reputation: 1459

Typescript extending array to return Max

You can do something like this:

class Person {
    constructor (public Name : string, public Age: number) {}
}

var list = new Array<Person>();
list.push(new Person ("Baby", 1));
list.push(new Person ("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);

but it would be nicer to do this:

list.Max( (a) => a.Age);

Suggestions on how to implement in a TypeScript generic?

Upvotes: 0

Views: 1933

Answers (1)

Robert Penner
Robert Penner

Reputation: 6408

Subclassing Array so we don't modify Array.prototype:

class List<Item> extends Array<Item> {
  Max<Selected>(select: (item: Item) => Selected): Item {
    return this.reduce( (a: Item, b: Item): Item => select(a) > select(b) ? a : b );
  }
}

class Person {
  constructor (public Name : string, public Age: number) {}
}

var list = new List<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.Max( (a) => a.Age)
alert(oldest_person.Name);

Try it in TypeScript Playground.

Upvotes: 2

Related Questions