scalawithcats / scala-with-cats

Source code for Scala with Cats
http://underscore.io/books/scala-with-cats
390 stars 129 forks source link

Suggestion for improvement to email check in Validation case study #224

Open nathanmbrown opened 1 year ago

nathanmbrown commented 1 year ago

Instead of creating a Check with specific logic for the splitEmail, why not leverage the existing containsOnce predicate and also the map method that the reader has taken time to implement in this exercise? Also there is no need to convert to an intermediate Tuple...

val splitEmail: Check[Errors, String, Array[String]] = Check(containsOnce('@')) map (_.split('@'))

val checkLeft: Check[Errors, String, String] =
  Check(longerThan(0))

val checkRight: Check[Errors, String, String] =
  Check(longerThan(3) and contains('.'))

val joinEmail: Check[Errors, Array[String], String] =
  Check { case Array(l, r) => (checkLeft(l), checkRight(r)).mapN(_ + "@" + _) }

val checkEmail: Check[Errors, String, String] =
  splitEmail andThen joinEmail