JSFiddle - React, Tailwind, and code Playground

by dimitrs_papadimitriou

JavaScript

Promise.prototype.map = function(mapping) {
  var initialPromise = this;
  return new Promise(function(resolve,reject) {
    initialPromise.then(result => resolve(mapping(result))).catch(reject)
  });
}
Promise.prototype.cata = function(alg) {
     return this.toEither().cata(alg); 
  }


const ok = (v) => ({
  v: v,
  map: (f) => ok(f(v)), 
  cata: (alg) => alg.ok(v),  
});

const error = (v) => ({
  v: v,
  map: () => error(v), 
  cata: (alg) => alg.error(v),  
});
 
var EitherCoyoAsync = function(actions, g) {
  this.g = g; 
  
  this.map = (f) => new EitherCoyoAsync(actions, x => f(this.g(x))); 
  
  this.bind = f =>{  
    var initialPromise = this;
    return new EitherCoyoAsync(function(resolve, reject) {
     actions(x => f(initialPromise.lower(x)).cata({ok:resolve,error:reject}) , x=>reject(x))
    }, x => x);
    
  }
  this.bindReader = computation =>{  
    var initialPromise = this;
    return new EitherCoyoAsync(function(resolve, reject) {
     actions(x => Reader(computation).runReaderP(initialPromise.lower(x)).cata({ok:resolve,error:reject}) , x=>reject(x))
    }, x => x);
    
  }
  this.cata = alg => actions(x => alg.ok(this.lower(x)), alg.error); 
 
  this.cataP = alg => {
    var initialPromise = this;

    return new Promise(function(resolve, reject) {
      actions(x => resolve(alg.ok( initialPromise.lower(x)) ) , x=>reject(alg.error(x)))
     }) ;
}
  this.lower = (v) => this.g(v);
}

Promise.prototype.toEither = function() {
  var initialPromise = this;
  var either = new EitherCoyoAsync(function(resolve, reject) {
    initialPromise.then(resolve).catch(reject)
  }, x => x);
  return either;
}

class IO {
    constructor(val) {
      this._fn = ()=>val;
      return this;
    }
    static fromFn(fn) {
      const ret = new IO();
      ret._fn = fn;
      return ret;
    }
    map(fn) {
      return IO.fromFn(()=>fn(this.runIO()));
    } 
    toPromise ()  { 
      var io = this;
      return new Promise(function(resolve) {
       ...