The power of functional programming

Today I am hacking away on GreyBox 3 (this is going to be a huge release, so I am going to skip 2.x versions). Anyway, something stumbled me: I love functional programming and functions should be first citizen in any programming language! I am going to insert more functional programming functions inside AJS.

First up is AJS.map. I wanted to improve AJS.showElement so it could take arbitrary elements, my first initial thing was this very trivial loop:

showElement: function() {
  for(var i=0; i<arguments.length; i++) {
    var elm = arguments[i];
    elm.style.display = '';
  }
},

Almost the same code had to be done to AmiJS.hideElement, then I figured that a map function would solve this pretty well, so I coded AJS.map:

map: function(list, fn) {
  for(var i=0; i<list.length; i++)
    fn(list[i]);
},

With this, AJS.showElement looks like:

showElement: function() {
  AJS.map(arguments, function(elm) { elm.style.display = ''});
},

Simply beautiful one liner!

Code · Code improvement · JavaScript 14. May 2006
© Amir Salihefendic. Powered by Skeletonz.