-
-
Save olivmonnier/905f270b99588ad3e564fb86cdc36ec1 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
| 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