Created
January 23, 2017 18:00
-
-
Save kevinmeredith/fec1dbad563cf5e19f12c68bb3380cc7 to your computer and use it in GitHub Desktop.
Generic Filter?
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
| trait Element[A, B] { | |
| val input: A | |
| val filteredValue: Option[B] | |
| } | |
| def filterFn[A, B](queryFilterValues: List[B])(implicit ev: A => Element[A, B]): List[A] => List[A] = | |
| elements => { | |
| queryFilterValues match { | |
| case _ :: _ => elements.flatMap { e => | |
| ev(e).filteredValue match { | |
| case Some(v) => if(queryFilterValues.contains(v) ) List(e.input) else List.empty | |
| case None => List.empty | |
| } | |
| } | |
| case Nil => elements.map(_.input) | |
| } | |
| } | |
| case class Person(name: Option[String]) | |
| object Person { | |
| implicit def personToElement(p: Person) = new Element[Person, String] { | |
| val input = p | |
| val filteredValue = p.name | |
| } | |
| } | |
| val joe = Person( Some("joe") ) | |
| val nameFilters = List( "jane", "joe", "will" ) | |
| scala> filterFn[Person, String]( nameFilters ) | |
| res7: List[Person] => List[Person] = <function1> | |
| scala> res7( List(joe) ) | |
| res8: List[Person] = List(Person(Some(joe))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment