JSFiddle - React, Tailwind, and code Playground
by dimitrs_papadimitriou
JavaScript
const ok = v => ({
map: f => ok(f(v)),
bind: f => f(v),
cata: alg => alg.ok(v)
});
const error = v => ({
map: () => error(v),
bind: () => error(v),
cata: alg => alg.error(v)
});
var safeTry = f => {
try {
return ok(f());
} catch (e) {
return error(e);
}
};
var reader = view => ({
run: c => view(c),
safeRun: safeTry(() => view(c))
});
const id = x => x;
const compose = (...fns) => fns.reduceRight((g, f) => x => g(f(x)), x => x);
const composeM = (...fns) => fns.reduceRight((g, f) => x => g(x).bind(f), ok);
const EitherAsync = (actions, res, rej) => ({
map: (f) => EitherAsync(actions, composeM(x => ok(x).map(f), res), rej),
mapError: (f) => EitherAsync(actions, res, compose(f, rej)),
bind: f => EitherAsync(actions, composeM(f, res), rej),
app: fv => EitherAsync(actions, composeM(f => fv.map(f), res), rej),
cata: alg => actions(x => res(x).cata(alg), compose(alg.error, rej)),
toEither: () => EitherAsync(actions, res, rej),
});
Promise.prototype.toEither = function () {
return EitherAsync((resolve, reject) => this.then(resolve).catch(reject), ok);
}
var delay = (x, t) => new Promise((res, rej) => setTimeout(() => {
res(x)
}, t))
var r =
Promise.resolve(0)
.toEither()
//.app(delay(4, 2000).toEither())
.map(x => x + 4)
setTimeout(() => {
console.log("cata")
r.cata({
ok: v => console.log(v),
error: v => console.log("left" + v)
});
}, 1000)
// var r = (composeM(composeM(x => ok(x).map(x => x + 3), x => ok(x).map(x => x + 3)), x => ok(x).map(x => x + 3))(4))
// .cata({
// ok: v => console.log(v),
// error: v => console.log("left" + v)
// });
// var delay = (x,t)=>new Promise((res,rej)=>setTimeout(() => {rej(x)}, t))
// var r = delay( 5,2000).toEither()
// .map(x => x + 4)
// .bind(y => delay(y+5,1000).toEither())
// .map(x => x + 4)
// setTimeout(() => {
// console.log("cata" )
// r.cata({
// ok: v => console.log(v),
// error: v => console.log("left"...