Posts tagged “Javascript”.

Javascript Lambda Expressions

I’ve been working with Linq lately and wished that I could use it in other languages. Since I code in Javascript a good bit and it’s a prototype language, I figured I could add the Linq functionality to the Javascript Array object through it’s prototype.

I’ll start with my target, which is the ability to do something like:

var a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ] ;     
 
// use lambda expression to filter out odd numbers
var a2 = a.where( "( n ) => n % 2 == 0" );

First, I need to parse out the C# style Lambda expression into function arguments and body.

The following regular expression should do the trick:

/\((.*)\)\s*=>\s*(.*)/

In a nutshell: look for an open parenthesis, skip it, capture everything that isn’t a close parenthesis and save it. Then skip the close parenthesis, ‘=>’ and white space and capture everything that’s left.
More… »