Tuesday, December 10, 2013

Chains and Flattened Arrays

The Lodash JavaScript utility library has plenty of array and collection functions, such as _.flatten(). Often, we end up having to apply several of these functions in succession in order to end up with the desired result. This becomes a much simpler programming task when using the _.chain() function to setup a chainable object first. The end result is a less awkward approach to successive function calls on the same object.

For example, consider the following data structure and the code used to extract the unique action strings from each object in the array.

var data = [
    {
        name: "Item 1",
        actions: [ "Create", "Read", "Delete" ]
    },
    {
        name: "Item 2",
        actions: [ "Create", "Update", "Delete" ]
    },
    {
        name: "Item 3",
        actions: [ "Delete" ]
    }
];

var actions = _.chain( data )
               .flatten( "actions" )
               .uniq();

Here, the resulting actions array is actually a chainable object — it has the array inside. The chainable object is actually setup by calling _.chain( data ). Then we flatten the actions property into a single array, then we remove duplicates. From this point on, we could start the chaining process all over again on the actions object. A nice side-effect is not having your code littered with underscores.

No comments :

Post a Comment