Skip to content

Instantly share code, notes, and snippets.

@rajasharan
Last active October 11, 2017 03:24
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 rajasharan/4e44af7e030e74c5068756d6306b534e to your computer and use it in GitHub Desktop.
Save rajasharan/4e44af7e030e74c5068756d6306b534e to your computer and use it in GitHub Desktop.
Simple Functor and Monad example for string manipulation

Functors & Monads in simple JS

Consider this contrived example of string manipulation. We want to convert a string to uppercase and append "!".

Procedural style code:

function test(str) {
  return str.toUpperCase() + "!";
}

console.log(test("hello"));
// HELLO!

My Box Functor/Monad

Let's decouple the two operations using a functional style

let Box = function(x) {
  let err = false;
  if (!x) err = true;
  return {
    map: f => err? Box(x): Box(f(x)),
    flatMap: f => err? Box(x): f(x),
    subscribe: (f, g) => err? g("Input Missing"): f(x)
  };
};

How to use Box

Box("hello")
  .map(s => s.toUpperCase())
  .map(s => s + "!")
  .subscribe(success => console.log(success), 
             error => console.log(error));

// HELLO!
Box("hello")
  .flatMap(s => Box(s.toUpperCase()))
  .flatMap(s => Box(s + "!"))
  .subscribe(success => console.log(success), 
             error => console.log(error));

// HELLO!
Box()
  .map(s => s.toUpperCase())
  .flatMap(s => Box(s + "!"))
  .subscribe(success => console.log(success), 
             error => console.log(error));

// Input missing

References

Further Reading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment