Skip to content

Instantly share code, notes, and snippets.

@getify
Created January 2, 2024 17:53
Show Gist options
  • Save getify/d9acaa0fcdc629ab746c1018f6bb21c0 to your computer and use it in GitHub Desktop.
Save getify/d9acaa0fcdc629ab746c1018f6bb21c0 to your computer and use it in GitHub Desktop.
minimal POC for Reader monad in JS
var r = Reader();
console.log(
r
.map(env => ({ ...env, y: 2 }))
.chain(env => Reader(() => ({ ...env, z: 3 })))
.evaluate({ x: 1 })
);
// { x: 1, y: 2, z: 3 }
function Reader(evaluate = v => v) {
return { map, chain, evaluate };
function map(mapFn) {
return chain(env => Reader(() => mapFn(env)));
}
function chain(chainFn) {
return Reader(env => {
var env2 = evaluate(env);
return chainFn(env2).evaluate(env2);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment