Skip to content

Commit

Permalink
Impl : Impl Filter And TestCode
Browse files Browse the repository at this point in the history
  • Loading branch information
myeonginwoo committed Dec 15, 2016
1 parent ef3c4c7 commit 1c01166
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Either/src/main/kotlin/LeftProjection.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,12 @@ class LeftProjection<out L,out R>(val value: L) {
fun <X> map(f: (L) -> X): LeftProjection<X, R> {
return LeftProjection(f(value))
}

fun filter(predicate: (L) -> Boolean) : L? {
return if(predicate(value)) {
return value
} else {
null
}
}
}
8 changes: 8 additions & 0 deletions Either/src/main/kotlin/RightProjection.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,12 @@ class RightProjection<out L, out R>(val value: R) {
fun <X : Any> map(f: (R) -> X): RightProjection<L, X> {
return RightProjection(f(value))
}

fun filter(predicate: (R) -> Boolean) : R? {
return if(predicate(value)) {
return value
} else {
null
}
}
}
16 changes: 16 additions & 0 deletions Either/src/test/kotlin/EitherTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,20 @@ class EitherTest {
assertEquals(123.0, either.right?.map(Int::toDouble)?.get)
assertEquals(246, either.right?.map { it * 2 }?.get)
}

@Test fun leftFilterTest() {
val either: Either<String, Int> = Left("left")

assertEquals(either.left?.filter { it.length > 3 }, "left")
assertEquals(either.left?.filter { it.length > 5 }, null)
assertEquals(either.left?.filter { it.length > 5 } ?: "default", "default")
}

@Test fun rightFilterTest() {
val either: Either<String, Int> = Right(126)

assertEquals(either.right?.filter { it > 100 }, 126)
assertEquals(either.right?.filter { it < 100 }, null)
assertEquals(either.right?.filter { it < 100 } ?: -1, -1)
}
}

0 comments on commit 1c01166

Please sign in to comment.