Last active
February 21, 2018 09:44
-
-
Save markwithers/d3e34ba028fb34a17fb6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
{ | |
"name": "state-test", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "Mark", | |
"license": "ISC", | |
"dependencies": { | |
"fantasy-states": "^0.2.1", | |
"ramda": "^0.19.1", | |
"ramda-fantasy": "^0.4.1" | |
}, | |
"devDependencies": { | |
"babel": "^5.8.23" | |
} | |
} |
This file contains hidden or 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, curry} 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 => { | |
console.log("side effect") | |
return get.map(prefs => html(baby, prefs)) | |
} | |
const tapS = curry((fn, arg) => get | |
.map(state => fn(state, arg)) | |
.map(always(arg)) | |
) | |
const drawBaby = composeK( | |
drawPage, | |
tapS(console.log), | |
updatePrefs, | |
tapS(console.log), | |
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