-
-
Save getify/d9acaa0fcdc629ab746c1018f6bb21c0 to your computer and use it in GitHub Desktop.
minimal POC for Reader monad in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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