Skip to content

Instantly share code, notes, and snippets.

@polarity
Created March 19, 2014 10:26
Show Gist options
  • Save polarity/9639080 to your computer and use it in GitHub Desktop.
Save polarity/9639080 to your computer and use it in GitHub Desktop.
Functional Programming Javascript: Composing with underscore

Functional Programming Javascript: Composing with underscore

From the underscore.js documentation :

Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

So what compose() basically does is, glueing functions together and returning a new function. Thats a really functional approach i like. You dont deal with passing around data, instead you declare some functions into a new one and apply it to your content.

Lets say you have some "useful", small standalone functions:

    var replacePipeWithSpace = function(str) {
      return str.replace("|", " ");
    }
    
    var getFirstChar = function(str) {
      return str.substr(0,1);
    }

And your like: Well let´s combine them. Normally you would do something like:

    var replaceAndGetFirstChar = function(str){
            return getFirstChar(replacePipeWithSpace(str));
    }

but it´s easier with compose:

    var replaceAndGetFirstChar = _.compose(getFirstChar, replacePipeWithSpace);
    
    replaceAndGetFirstChar("Hello|World"); // "h"

I stumpled upon this in a talk by Brian Lonsdorf and his rant about underscore.js and functional programming. It really gave me some gotchas on the functionl programming topic. Also look at his slides Functional Patterns for the non-mathematician This gist ist just trying to wrap my head around it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment