Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET
Tip/Trick

LINQ2TypeScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
20 Mar 2014CPOL 23.1K   15   6
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)


Written By
Software Developer (Senior) http://www.ansibleww.com.au
Australia Australia
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.

Comments and Discussions

 
QuestionCheck out IXJS Pin
David Hanson24-Mar-14 11:11
David Hanson24-Mar-14 11:11 
AnswerRe: Check out IXJS Pin
Super Lloyd24-Mar-14 13:01
Super Lloyd24-Mar-14 13:01 
QuestionNice Pin
Sacha Barber21-Mar-14 1:50
Sacha Barber21-Mar-14 1:50 
AnswerRe: Nice Pin
Super Lloyd21-Mar-14 20:11
Super Lloyd21-Mar-14 20:11 
GeneralSuper! Pin
Meshack Musundi20-Mar-14 22:59
professionalMeshack Musundi20-Mar-14 22:59 
GeneralRe: Super! Pin
Super Lloyd21-Mar-14 20:13
Super Lloyd21-Mar-14 20:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.