Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

6/14/2013

A taste of functional javascript

There is some real power in functional programming, compared to imperative which is a basis for OOP paradigm. One of them is immutable state.
In a languages that supports state change ( imperative family ) mutability is a double edged sword - you can create awesome control flow ( if you know ) or you can quickly get lost in a jungle of your own variables.
Functional paradigm elegantly avoids state change, by not separating function from the value that is returned. So in FP ( functional programming ) function IS a value. There are some variations and some languages supports state change and mutability to the certain degree, but when we talk about FP we think mostly about functions that are values.

Here is one example of FP. It is written first in Coffeescript, and then in vanilla Javacript:

# data
arr = ["chicken","pig","donkey","horse","cow"]

#main function definition
each = (data,iterator,transform)->
    iterator(data,transform)

#transformer
toUpper=(args)->
    console.log args.toUpperCase() + " farm"

#iterator
iterate = (data,upper)->
    for key,val in data
        upper(key)

#call everything
each(arr,iterate,toUpper)
#

Vanilla Javascript ( compiled ):
// Generated by CoffeeScript 1.6.2
(function() {
  var arr, each, iterate, toUpper;

  arr = ["chicken", "pig", "donkey", "horse", "cow"];

  each = function(data, iterator, transform) {
    return iterator(data, transform);
  };

  toUpper = function(args) {
    return console.log(args.toUpperCase() + " farm");
  };

  iterate = function(data, upper) {
    var key, val, _i, _len, _results;

    _results = [];
    for (val = _i = 0, _len = data.length; _i < _len; val = ++_i) {
      key = data[val];
      _results.push(upper(key));
    }
    return _results;
  };

  each(arr, iterate, toUpper);

}).call(this);
//
Notice the elegance of  functions passing as arguments to other functions, without effecting anything outside them. It is called function composition, and it is the main "sugar" of FP.

Happy Coding


No comments:

Post a Comment