arrays - What's the equivalent of type-specific extension methods in JavaScript? -
say have class person
. definition following:
function person(name, age) { this.name = name; this.age = age; }
now have array of persons
(or people) , want find oldest one. in c#, via extension methods:
person oldest(this ienumerable<person> people) => people.orderbydescending(p => p.age).first(); // usage: var elder = people.oldest();
what's equivalent in javascript? far, able come with:
array.prototype.oldest = function() { return this.slice().sort(function(left, right) { return left.age - right.age; }).pop(); };
this works , has same syntax c#, has few drawbacks:
1) modifies prototype of builtin, potentially lead conflicts other libraries so.
2) not type-safe: it's easy accidentally call on array doesn't contain people, lead runtime error.
alternatively, define this:
function oldest(people) { // ... }
but have call oldest(people)
instead of people.oldest()
, hamper readability.
is there type-safe, syntactically "nice" way in javascript i'm missing?
because js isn't type safe, you're better off implementing method oldest(people)
...
just think of decorator pattern - legit approach projecting functionality unknown set of related entities.
then - can type-checking within function.
you namespace make syntax more "obvious" if that's concern guess:
personlist(persons).getoldest()
as 1 objective-c-ish example.
then, can add type-specific checking creator personlist:
function personlist(persons) { //iterate on persons , make sure //it's valid. return undefined or {} if not. return { getoldest: function() { // insert clever code here ... persons.slice().dice().puree(); }, getyoungest: function() { //even more clever code here ... } } }
with approach, code
personlist(cats).getoldest()
with throw 'getoldest undefined' error -- makes easy spot problem when have 11,000,000 lines of js code sort through.
it has added advantage of making c# inner-child feel more @ home (with js file called "arrayextensions.persons.js" in project folder). feels "chicken soup c# soul," right?
Comments
Post a Comment