views:

65

answers:

3

I doubt this is possible, and I'm certain to do it in a production environment would be an impressively bad idea. This is just one of those hypothetical "I-wonder-if-I-could..." things.

I was wondering if it is possible to modify or extend how the browser JavaScript engine parses the code at run-time. For example: if I tried to use C# style lambda syntax in JavaScript:

var x = myJsObjCollection.Where(a=>a.ID == 2);

Could I modify the parsing of the script and intercept the lambda code and parse it myself?

+1  A: 

There's no direct way to do this in JavaScript. The closest you could get would be to write your own eval type function which would interpret whatever code you want.

Or, get the V8 JavaScript engine source code, make some changes to that, and see if you can get it implemented in Chrome somehow :)

Bob
The custom eval idea is good. Something like `lambdaEval("a=>a.ID == 2");`. But it would be a lot of parsing.
Joel Potter
check my answer re: functional.js :-)
Pointy
+3  A: 

I doubt it.

The engine which parses and executes the javascript is on the client's browser, and as such cannot be modified or changed by any website (I would hope).

Potentially you could use javascript supported types and syntax to describe a lambda expression and then have your own javascript library which expands it to valid javascript calls.

However, it would not be that useful since javascript functions are already super flexible. Your code above in valid JS would look like the equivalent c# delegate:

var x = myJsObjCollection.Where(function() { if (this.ID == 2) return this; });

Which isn't a whole lot more work to type.

Update

To take Bob's Idea a couple steps further, you could potentially write something like this:

function lambda(vName, comparison)
{
    var exp = new RegExp("\\b" + vName + "\\.", "g");
    comparison = comparison.replace(exp, "arg.");
    return function(arg) {
        var result;
        eval("result = " + comparison + ";");
        return result;
    };
}

Then your Where function would look something like:

Array.prototype.Where = function(lambdaFunc) {
    var matches = [];    
    for (var i in this)
    {
        if (lambdaFunc(this[i]))
            matches[matches.length] = this[i]
    }
    return matches;
};

And you could call it:

var x = myJsObjCollection.Where(lambda("a", "a.ID == 2"));

Working example at http://jsbin.com/ifufu/2/edit.

Joel Potter
Cool. You could also call split so that you could leave the lambda argument as just a string like "a => a.ID === 2" and split on "=>"...Might need some parsing to trim away spaces
Bob
+1  A: 

The answer is pretty much "no", but check this out: http://osteele.com/sources/javascript/functional/ and in particular the stuff about string -> function "coercion".

Pointy
That's pretty cool!
Joel Potter