Created
June 20, 2016 09:05
-
-
Save markwithers/51389cfd7197529fe89f0baedf046a7e to your computer and use it in GitHub Desktop.
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
import {StateT} from "fantasy-states" | |
import {Future} from "ramda-fantasy" | |
import {compose, composeK, merge, always} from "ramda" | |
// Make a new monad from Future and StateT (State Transformer) | |
const StateF = StateT(Future) | |
const {get, modify} = StateF | |
const babies = [ | |
{id: 2, name: "Alice", sex: "F"}, | |
{id: 3, name: "Bob", sex: "M"}, | |
] | |
const isFemale = baby => baby.sex === "F" | |
// Simulate async operation to fetch data | |
const findBaby = i => new Future((reject, resolve) => | |
babies[i] ? resolve(babies[i]) : reject("None Found") | |
) | |
// Update metadata in 'state' to reflect preferred colours | |
const updatePrefs = baby => modify(merge({bgColor: isFemale(baby) ? "pink" : "blue"})) | |
.map(always(baby)) | |
const html = (baby, prefs) => ` | |
<div style={background-color: ${prefs.bgColor}, font: ${prefs.font} }> | |
${baby.name} | |
</div>` | |
const drawPage = baby => get.map(prefs => html(baby, prefs)) | |
const drawBaby = composeK( | |
drawPage, | |
updatePrefs, | |
compose(StateF.lift, findBaby) // lift a Future to a StateF | |
) | |
drawBaby(StateF.of(0)) // use stateF.of to generate monadic value | |
.evalState({font: "cursive"}) // initialise the state and start the processing | |
.fork(console.log, console.log) // like 'then' and 'catch' from a Promise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment