Skip to content

Commit dc8e02a

Browse files
committed
adding filter to Tription
1 parent 34082aa commit dc8e02a

2 files changed

Lines changed: 17 additions & 4 deletions

File tree

src/main/scala/spray/json/Tription.scala

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,12 @@ sealed abstract class Tription[+T] extends Product
2525
else if( isNull ) Null
2626
else f( get )
2727

28+
/** return `Null` (not `Undefined`) if filter criteria don't match **/
29+
final def filter(p: T => Boolean): Tription[T] =
30+
if (!hasValue || p(this.get)) this else Null
31+
2832
final def foreach[U](f: T => U): Unit =
2933
if( hasValue ) f( this.get )
30-
31-
// not sure whether to return Null or Undefined if the filter criteria are not met
32-
// final def filter(p: T => Boolean): Tription[T] =
33-
// if (!hasValue || p(this.get)) this else (Undefined/Null)
3434
}
3535

3636
case class Value[+T](x: T) extends Tription[T] {

src/test/scala/spray/json/TriptionSpec.scala

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,19 @@ class TriptionSpec extends Specification
7676
Null.flatMap( mapFunction ) mustEqual Null
7777
Value(value).flatMap( mapFunction ) mustEqual Value(value + append)
7878
}
79+
"filter returns itself for Null and Undefined" in {
80+
Undefined filter { _ => false } mustEqual Undefined
81+
Null filter { _ => false } mustEqual Null
82+
Undefined filter { _ => true } mustEqual Undefined
83+
Null filter { _ => true } mustEqual Null
84+
}
85+
"filter returns Null if value does not match criteria" in {
86+
Value(nextString) filter { _ => false } mustEqual Null
87+
}
88+
"filter returns itself if value matches criteria" in {
89+
val value = nextString
90+
Value(value) filter { _ => true } mustEqual Value(value)
91+
}
7992
"foreach executes for value in a Value and does nothing otherwise" in {
8093
val sb = new StringBuilder
8194
def foreachFunction( x: Any ) = sb.append( x.toString )

0 commit comments

Comments
 (0)