Introduction
This tip gives some ideas to bring some of the C# LINQ goodness to TypeScript (and, by extension, JavaScript).
Using the Code
While starting to get seriously into client side and JavaScript heavy application, I started to seriously miss the concise way LINQ was simplifying working with collection.
Not to worry, we can do it in JavaScript too! Even better, we can do it in a strongly typed way in TypeScript!
Here I intend to show how to extend JavaScript array with .where()
and .select()
!
var names = item.where(x => x.ID > 5).select(x => x.Name)
Well, why not? Here is the TypeScript definition of those methods!
interface Array<T> {
select<U>(cvt: (item: T) => U): Array<U>;
where(predicate: (item: T) => boolean): Array<T>;
}
Array.prototype.where = function <T>(predicate: (item: T) => boolean): Array<T> {
var result = [];
for (var i = 0; i < this.length; i++) {
var item = this[i];
if (predicate(item))
result.push(item);
}
return result;
};
Array.prototype.select = function <T, U>(cvt: (item: T) => U): Array<U> {
var result = [];
for (var i = 0; i < this.length; i++) {
var item = this[i];
var ci = cvt(item);
result.push(ci);
}
return result;
};
History
This is the first draft.
The Australia born French man who went back to Australia later in life...
Finally got over life long (and mostly hopeless usually, yay!) chronic sicknesses.
Worked in Sydney, Brisbane, Darwin, Billinudgel, Darwin and Melbourne.