Promise as Monad : Monadic Laws

https://github.com/eu81273/jsfiddle-console

by dimitrs_papadimitriou

HTML

<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>

JavaScript

// Monad Laws-Rediscovering Promises in Javascript
 //https://medium.com/@dimpapadim3/promises-made-simple-in-javascript-db9e3bc39537 
 var Promise = function(resolve) {
   this.then = function(callback) {
     resolve(callback);
   }
   this.map = function(func) {
     var initialPromise = this;
     return new Promise(function(resolve) {

       initialPromise.then(result => resolve(func(result)))
     });
   }
   this.bind = function(func) {
     var initialPromise = this;
     return new Promise(function(resolve) {
       initialPromise.then(result => func(result).then(x => resolve(x)))
     });
   }
 }

 var id = x => new Promise((resolve) => resolve(x));
 
 // Law 1 -Left identity: return a >>= f ≡ f a
 var value = 1 
 var f = x => id(x * 2);
 //id(value).bind(f) ==f(value) 
 id(value).bind(f).then(console.log)
 f(value)         .then(console.log)

 // Law 2 -Right Identity : m >>= return ≡ m
 var m = id(1)
 //m.bind(id) == m
 m.bind(id).then(console.log)
 m         .then(console.log)

 //Law 3 -Associativity: (m flatMap f) flatMap g assert_=== m flatMap { x => f(x) flatMap {g} }
 var m = id(1);
 var f = x => id(x * 2);
 var g = x => id(x * 5);
 
 m.bind(f).bind(g)         .then(console.log); 
 m.bind(x=>f(x).bind(g))   .then(console.log);