Imagine you have a class named Person
. Its structure is as follows:
function Person(name, age) {
this.name = name;
this.age = age;
}
Now, suppose you have an array of Persons
(or individuals) and you wish to identify the oldest one. In C#, you can achieve this using extension methods:
Person Oldest(this IEnumerable<Person> people) =>
people.OrderByDescending(p => p.Age).First();
// Example:
var elder = people.Oldest();
How would you accomplish the same task in JavaScript? Below is what I could come up with so far:
Array.prototype.oldest = function() {
return this.slice().sort(function(left, right) {
return left.age - right.age;
}).pop();
};
Although this method works effectively and resembles the syntax used in C#, it does have some drawbacks:
1) It alters the prototype of a built-in object, which might cause conflicts with other libraries doing the same.
2) It lacks type safety: there's a risk of mistakenly invoking it on an array that doesn't contain people, resulting in runtime errors.
Another approach could be defining it like this:
function oldest(people) {
// ...
}
However, calling it as oldest(people)
instead of people.oldest()
could reduce readability.
Is there a more type-safe and aesthetically pleasing way to accomplish this task in JavaScript that I might be overlooking?