Functional Javascript Programming using Underscore

Aug 10 2011

The Scenario

Suppose a javascript function is needed to parse text and execute another function for certain lines of text. Each line of the text is ended with a line break. If there is a keyword ‘get’, then the word following it needs to be checked if it is in the list of files on the server, and get it, using a GET request. So ‘get this’ would get the file ‘this’ from the server.

Object Oriented Approach

First, I tried doing this using the traditional way, with array indexes of letters.

if(input.value.split(' ').indexOf('get')==-1) return;
var lines = input.value.split('\n');

I stopped right there the next line is supposed to be a for each loop. That satisfied the requirements for using a functional library called underscore.js.

Mixed Approach

Not my favorite one, as it makes the painting look like a collage, and I think it made an error in the code harder to spot. See if you can spot it:

_(input.value.split(' ')).chain()
    .select(function (line) {
        var words = line.split(' ');
        return words.length > 1 && words[0] == 'get' && _.include(files, words[1]);
    .each(function (line) {

Aha! The space should actually be newline.

Functional Approach
This time, I had to modify the code to use a single word from the word array, the last one.
The main line that violated the functional approach was

var words = line.split(' ');

along with the array accesses, which should be replaced with first and rest. It turns out there is a purely functional way:

    .map(function (line) {
        return line.replace(/get\s*/, '');
    .select(function (module) {
        return module in files;
    .each(function (module) {

The custom executeGet function has been replaced by jQuery’s $.get.

Which approach is better? Using the OO approach, a local index variable would be needed to be created for the for loop, along with other locals, which adds irrelevant lines to the code. On the other hand, each line on its own makes sense. However, functional code cannot be understood except as a whole, because there are no variables. Statelessness has its own beauty in programming. It’s similar to running a quantum computer, not caring how bits disappear or time warp, but only for the result of the computation.

No responses yet