Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

LINQ2TypeScript

5.00/5 (3 votes)
20 Mar 2014CPOL 23.9K  
Some ideas to bring LINQ goodness to JavaScript array

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() !

JavaScript
// wouldn't it be nice to write
var names = item.where(x => x.ID > 5).select(x => x.Name)  

Well, why not? Here is the TypeScript definition of those methods!

JavaScript
interface Array<T> {
    select<U>(cvt: (item: T) => U): Array<U>;
    where(predicate: (item: T) => boolean): Array<T>;
}
/** return a subset of an array matching a predicate */
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;
};
/** convert an array to another one */
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)