Skip to content

Instantly share code, notes, and snippets.

@3v0k4
Last active December 21, 2019 00:08
Show Gist options
  • Select an option

  • Save 3v0k4/4f8a438456d148839caa4fc5bed22c50 to your computer and use it in GitHub Desktop.

Select an option

Save 3v0k4/4f8a438456d148839caa4fc5bed22c50 to your computer and use it in GitHub Desktop.
const Right = x =>
({
x,
map: f => Right(f(x)),
inspect: _ => `Right(${x})`,
isLeft: _ => false,
chain: f => f(x),
})
const Left = x =>
({
x,
map: f => Left(x),
inspect: _ => `Left(${x})`,
isLeft: _ => true,
chain: f => Left(x)
})
const tryCatch = f => {
try {
return Right(f())
} catch (e) {
return Left('could not parse')
}
}
const fromNullable = (error, a) =>
(a === undefined || a === null) ? Left(error) : Right(a)
const first = xs => fromNullable('empty array', xs[0])
const parse = s => tryCatch(() => JSON.parse(s))
const upper = s => s.toUpperCase()
const shout = s => s.concat('!')
const format = s => Right(s).map(upper).map(shout)
const functional = s => Right(s).chain(parse).chain(first).chain(format)
functional('["hello", "world"]')
// Right(HELLO!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment