or learn more

Pointless programming in JavaScript

Apr 10, 2013

Using Underscore and Lemonad, how could you write a run-length encoder/decoder without ever referencing a function parameter?

One way:

var S = ['a', 'a', 'a', 'a', 
         'b', 'c', 'c', 
         'a', 'a', 'd', 
         'e', 'e', 'e', 'e'];

var pack = L.partial1(L.partitionBy, _.identity);

//=> [['a', 'a', 'a', 'a'], ['b'] ...]

var rle = _.compose(

//=> [[4, 'a'], [1, 'b'], [2, 'c'], 
      [2, 'a'], [1, 'd'], [4, 'e']]

var rld = _.compose(

L.pipeline(S, rle, rld);

//=> ["a", "a", "a", "a", "b", ...]

The above style is called “point-free” style where “points” refer to function parameters like a and b in the function function(a, b) { ... }. The functions rle and rld are built entirely via the composition functions in Lemonad and Underscore1. Fun fun.js.

I’ll cover point-free style to a small degree in my upcoming book on functional JavaScript, but it’s a fun way to think about building programs and I encourage you to explore.

I have a gist with the same code for syntax highlighting and different spacing.

  1. Underscore has for a while had the _.compose function, but is only now incorporating other composition functions like _.partial and (maybe) _.flip

One Comment, Comment or Ping

  1. Igor

    Thanks for not embedding the gist to your awesome declarative blog. :-) People do it all the time and I can’t read their blogs with w3m.

Reply to “Pointless programming in JavaScript”