Skip to content

Instantly share code, notes, and snippets.

@itspoma
Last active July 18, 2016 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itspoma/6a3d7f87e0fd0e0ed79c5ae502070474 to your computer and use it in GitHub Desktop.
Save itspoma/6a3d7f87e0fd0e0ed79c5ae502070474 to your computer and use it in GitHub Desktop.
JS Functional Programming

Monads

function Monad(modifier) {
  return function unit(value) {
    var monad = Object.create(null);
    monad.bind = function (func) {
      return func(value);
    }
    return monad;
  }
}

var idnt = Monad();
var monad = idnt('test');
monad.bind(console.log);

Maybe Monad

function Monad(modifier) {
  var prototype = Object.create(null);
  function unit(value) {
    var monad = Object.create(prototype);
    monad.bind = function (func, args) {
      return func(value, ...args);
    }
    if (typeof modifier == 'function') {
      modifier(monad, value);
    }
    return monad;
  }
  return unit;
}

var maybe = Monad(function (monad, value) {
  if (value === null || value === undefined) {
    monad.is_null = true;
    monad.bind = function () {
      return monad;
    }
  }
}
var monad = maybe(null);
monad.bind(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment