JSFiddle - React, Tailwind, and code Playground

by dimitrs_papadimitriou

JavaScript

//Rediscovering Promises in Javascript
//https://medium.com/@dimpapadim3/promises-made-simple-in-javascript-db9e3bc39537
//https://youtu.be/uPpTOwA2vXU

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()));
  }
  flatten() {
    return IO.fromFn(()=>this.runIO().runIO());
  }
  runIO() {
    return this._fn();
  }


}

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

Promise.prototype.map = function(mapping) {
  var initialPromise = this;
  return new Promise(function(resolve) {
    initialPromise.then(result => resolve(mapping(result)))
  });
}

 var compose = f=>g=>x=>f(g(x));
var prop =name=>x=>x[name];

 Promise.resolve({name:`j`}).then(IO.fromFn(console.log).map(prop("name")));


var r = compose(console.log)(prop("name"));

var t  = x=>
new IO(x) 
.map(prop("name"))
.map(console.log);

var tt =Promise.resolve({name:`j`}).then(t) ;

 

//r({name:`j`});