Skip to content

Instantly share code, notes, and snippets.

@evilsoft
Last active October 6, 2016 00:58
Show Gist options
  • Save evilsoft/0e7b134f2a1f21f6aaf54a37c6b18ccd to your computer and use it in GitHub Desktop.
Save evilsoft/0e7b134f2a1f21f6aaf54a37c6b18ccd to your computer and use it in GitHub Desktop.
// I use flat map for a couple cases. I hope demonstrates
// a practical use case for flatMapping.
// IO is a way to capture a flow that is dependent on some side-effect.
// grabbing from and writing to a global (yuck!) for instance also logging to a console.
// We want to control these side effects. So if I have a flow that does multiple
// side-effects, chain is the way to go to compose them together and not run them
// until I call run on that IO.
const { IO, compose, curry, constant, map, chain } = crocks
// getLocPropIO : String -> IO
const getLocPropIO =
prop => IO(() => window.location[prop])
// setLocPropIO : String -> String -> IO
const setLocPropIO = curry(
(prop, x) => IO(() => window.location[prop] = x)
)
// logItIO : String -> IO
const logItIO =
x => IO(() => compose(constant(x), console.log.bind(console))(x))
// tail : String -> String
const tail =
x => x.slice(1)
// applyEvil : String -> String
const applyEvil =
x => x.concat('/evil')
// evilHash : String -> String
const evilHash =
compose(applyEvil, tail)
// evilDatHash : String -> IO
const evilDatHash = compose(
chain(setLocPropIO('hash')), // now update the hash (side-effecty)
map(evilHash), // strip the hash and add /evil
getLocPropIO // pull the prop from window (side-effecty)
)
const evilHashIO = evilDatHash('hash')
const evilHashLogIO = evilHashIO.chain(logItIO) // can extend that by chaining more IOs like a mad person
// run when I please
evilHashIO.run() // without logging
evilHashLogIO.run() // with logging
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment