Created
May 7, 2015 20:20
-
-
Save frohoff/db15cb9244e5a6184ab3 to your computer and use it in GitHub Desktop.
functional composition flow
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
object Test extends App { | |
lazy val flow: SplunkEvent => Seq[Email[Alert]] = | |
receiveEvent andTap rawTap andThen | |
convertToSecurityEvent andMaybeTap eventTap andMaybe | |
classifyIfTrained andMaybeTap classificationTap andMaybeSeq | |
aggregateByTimeWindow andForEach (_.sortBy(_.event.time)) andForEach | |
convertToAlert andForEachTap alertTap andForEachOpt | |
createEmail andForEachTap emailTap | |
} | |
package object flow { | |
implicit class RichFunction[A, B](f: Function1[A, B]) { | |
def andTap(g: B => Unit): Function1[A, B] = f andThen { b => g(b); b } | |
def sink: Function[A, Unit] = f andThen (_ => ()) | |
def forEach: Function[Traversable[A], Traversable[B]] = t => t.map(f) | |
def maybe: Function[Option[A], Option[B]] = o => o.map(f) | |
} | |
implicit class RichOptionFunction[A, B](f: Function1[A, Option[B]]) { | |
def andMaybe[C](g: B => C): Function1[A, Option[C]] = f andThen (_.map(g)) | |
def andMaybeFlat[C](g: B => Option[C]): Function1[A, Option[C]] = f andThen (_.flatMap(g)) | |
def andMaybeSeq[C](g: B => Seq[C]): Function1[A, Seq[C]] = f andThen (_ map g) andThen (_ getOrElse List()) | |
def andMaybeTap(g: B => Unit): Function1[A, Option[B]] = f andMaybe { b => g(b); b } | |
} | |
implicit class RichSeqFunction[A, B](f: Function1[A, Seq[B]]) { | |
def andForEach[C](g: B => C): Function1[A, Seq[C]] = f andThen (_ map g) | |
def andForEachFlat[C](g: B => Seq[C]): Function1[A, Seq[C]] = f andThen (_ flatMap g) | |
def andForEachOpt[C](g: B => Option[C]): Function1[A, Seq[C]] = f andThen (_ flatMap (g andThen (_.toSeq))) | |
def andForEachTap(g: B => Unit): Function1[A, Seq[B]] = f andThen (_ map (_ tap g)) | |
} | |
implicit class RichUnitFunction[A](f: A => Unit) { | |
def andAlso(g: A => Unit): A => Unit = tap(f) andThen g | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment