Last active
November 13, 2017 23:04
-
-
Save martinsson/0cc9c06f87357581bfcb24a293978926 to your computer and use it in GitHub Desktop.
Monadic version of the trip-service-kata by Sandro Mancuso, using Maybe and Either. Public interface still compatible
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 { Maybe, Either } = require('monet'); | |
class TripService { | |
// Monadic version of the public function, returns an Either | |
getTripsByUserEither(user, loggedUser) { | |
return Maybe.fromNull(loggedUser) | |
.toEither('User not logged in.') | |
.flatMap(connectedUser => this._doGetTripsByUser(user, connectedUser)); | |
// flatMap instead of map as the loadFromDb Returns an Either as well, ie an Either in an Either, needs to be flattened | |
} | |
// Imperative version, calling the monadic one, keeping the contract of throwing | |
getTripsByUserImperative(user, loggedUser) { | |
let eitherTrips = this.getTripsByUserEither(user, loggedUser); | |
return eitherTrips.cata( | |
failure => {throw new Error(failure)}, | |
trips => trips); | |
} | |
// doGetTripsByUser :: user -> user -> Either String (List Trip) | |
_doGetTripsByUser(user, loggedUser) { | |
let isFriend = user.isFriendsWith(loggedUser); | |
return isFriend ? this._loadTripsFromDb(user) : noTrips(); | |
} | |
// loadTripsFromDb :: user -> Either String (List Trip) | |
_loadTripsFromDb(user) { | |
return TripDAO.findTripsByUser(user); | |
} | |
} | |
function noTrips() { | |
return Either.Right([]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment