Alex Rivera | Logout

Monads in JavaScript

Asked 2012-08-08T18:43:21.750
35

So I want to understand the practical cases where monads in JavaScript are helpful.

I read a bunch on articles on Monads in JavaScript and understand that jQuery is one example of its use. But besides the "chaining" pattern, what other issues can be effectively solved using Monads in front-end engineering?

Ref:

http://importantshock.wordpress.com/2009/01/18/jquery-is-a-monad/

http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html

Edit
Report

1 Answer

1

Passing arguments to a given callback function within a particular scope can be generalized using a monad:

/* Unit function */
function Monad(value)
  {
  // Construct monad and set value to given argument or undefined
  this.value = value || undefined;
  }

/* Constructor function */
Monad.prototype.pass = function(value, cb, scope)
  {
  // return constructor result if no default value is passed
  if (/undefined/.test(this.value) )
    {
    return new this.constructor();
    }
  // return callback result for given value in given context if scope is passed
  if(scope)
    {
    /* Bind function */
    return cb.call(scope, value);
    }
  // return callback result for given value otherwise
  return cb(value);
  }

 /* Separate arguments from function, and function from global scope */
 var foo = new Monad(RegExp);
 var bar = foo.pass(2, Function("count","return ++count"), Math);

References

answered 2013-01-22T20:30:11.527

Your Answer