Get inspiration from .net’s LINQ in Javascript

When you think about working with enumerable stuff client-side, you can get great inspiration from .net’s awesome LINQ goodness.  For example, if you need a trivial way to sum up items in an array, you can bolt on a “sum” routine onto Arrays.  For example, here’s a small one, which has a default implementation to deal with strings or numbers:

Array.prototype.sum = function (predicate) {
    predicate = predicate || function (match) {
        if (typeof match == "string") {
            return match.length;
        }
        return match;
    };
    var result = 0;
    for (var i = 0; i < this.length; i++) {
        result += predicate(this[i]);
    }
    return result;
};

Here are a couple usage examples:

// Baked-in sum for strings
var array1 = ["hello","world"];
var length = array1.sum());

// Baked-in sum for numbers
var array2 = [10,20,30];
length = array2.sum();

// Custom for custom objects.
var array3 = [{yearsOfExperience:3},{yearsOfExperience:5}];
length = array3.sum(function(match){return match.yearsOfExperience;});

Here’s a Fiddle that demonstrates this (hit F12 in FF, Chrome, IE*+ and look at the console when running):  http://jsfiddle.net/harperj1029/Zeaqa/

Think Linq!

1 thought on “Get inspiration from .net’s LINQ in Javascript

Leave a reply to Rex Morgan (@rexm) Cancel reply