Reader View Templates example

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

by dimitrs_papadimitriou

HTML

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

JavaScript

var Reader = (expr) => ({
    expr: expr,
    map: f => Reader (env=>f(Reader(expr).run(env))) ,
    run: env => expr(env),  
    toEither:() =>{
      var initialPromise = this;
      var either = new EitherCoyoAsync(function (resolve, reject) {
        initialPromise.then(resolve).catch(reject)
      }, x => x);
      return either;
    }
  });

  
  var EitherCoyoAsync = function (actions, g) {
    this.g = g;

    this.map = (f) => new EitherCoyoAsync(actions, x => f(this.g(x)));
    this.cata = alg => actions(x => alg.ok(this.lower(x)), alg.error);
    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;
  }


  fetch("https://api.github.com/users")
    .map(response => response.json())
    .map(users => users.map(u => u.login))
    .toEither()
    .cata({
      ok: v => console.log(v),
      error: v => console.log("left" + v)
    });

  fetch("https://api.github.com/users")
    .then(response => response.json())
    .then(response => console.log('Success:', JSON.stringify(response)))
    .catch(error => console.error('Error:', error));