Archive for February, 2011

Usefulness of the Underscore.js functional library

I usually ignore new frameworks or libraries until I see it referenced more than a dozen times and Underscore has reached that threshold. Recently I needed some more powerful libraries for working with collections and due to time constraints I decided not to write additional functions but instead give this library a try. Many of the functions in Underscore are already present in modern browsers and when these functions are found the library will defer to the native implementation–this was a huge selling point for me.

To keep this post brief I’ll get to some samples of usage:

Some of the functions that I found useful recently were:

This function

_.pluck(_productCollection.Items, "Id"), function (Id) {
return Id === product.Id;
})

Transforms the Items[] from this object into

_productCollection = {
    CriteriaType: "Products",
    Items: {
        Facility: null,
        FacilityId: null,
        Name: "",
        Id: ""
    }
}

An array of Id’s for additional processing

[Id,Id,Id]

This was useful to me when I had to compare the values of Ids against a new value to see if it was already contained in the initial object.

!_.any(_.pluck(productCollection.Items, "Id"), function (Id) {
    return Id === product.Id;
}))

Another useful area was removing an item in a collection with the following code:

productCollection.Items = _.reject(productCollection.Items, function (prod) {
    return prod.Id === productId;
});

This is definitely a useful library.