Created
February 7, 2019 16:55
-
-
Save dmcg/7c77505eae0ab2fa9ffc220eb7f42d7e to your computer and use it in GitHub Desktop.
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
class PartitionTests : JUnit5Minutests { | |
override val tests = rootContext<Unit> { | |
test("empty input and predicates") { | |
val list = emptyList<Int>() | |
val predicates = emptyList<(Int) -> Boolean>() | |
val result = list.partition(predicates) | |
assertEquals(emptyList<List<List<Int>>>(), result) | |
} | |
test("empty input some predicates") { | |
val list = emptyList<Int>() | |
val predicates = listOf(::isNegative, ::isZero, ::isPositive) | |
val result = list.partition(predicates) | |
assertEquals(listOf(emptyList<Int>(), emptyList(), emptyList()), result) | |
} | |
test("items but no predicates") { | |
val list = listOf(-1, 0, 1, 2, 3) | |
val predicates = emptyList<(Int) -> Boolean>() | |
val result = list.partition(predicates) | |
assertEquals(emptyList<List<Int>>(), result) | |
} | |
test("not empty") { | |
val list = listOf(-1, 0, 1, 2, 3) | |
val predicates = listOf(::isNegative, ::isZero, ::isPositive) | |
val result = list.partition(predicates) | |
assertEquals(listOf(listOf(-1), listOf(0), listOf(1, 2, 3)), result) | |
} | |
test("a predicate doesn't match any item") { | |
val list = listOf(-1, 1, 2, 3) | |
val predicates = listOf(::isNegative, ::isZero, ::isPositive) | |
val result = list.partition(predicates) | |
assertEquals(listOf(listOf(-1), listOf(), listOf(1, 2, 3)), result) | |
} | |
test("an item doesn't match any predicate") { | |
val list = listOf(-1, 0, 1, 2, 3) | |
val predicates = listOf(::isNegative, ::isPositive) | |
val result = list.partition(predicates) | |
assertEquals(listOf(listOf(-1), listOf(1, 2, 3)), result) | |
} | |
test("input order is preserved") { | |
val list = listOf(3, 2, 1, 0, -1) | |
val predicates = listOf(::isNegative, ::isZero, ::isPositive) | |
val result = list.partition(predicates) | |
assertEquals(listOf(listOf(-1), listOf(0), listOf(3, 2, 1)), result) | |
} | |
} | |
} | |
fun isNegative(x: Int) = x < 0 | |
fun isZero(x: Int) = x == 0 | |
fun isPositive(x: Int) = x > 0 | |
fun <T> Iterable<T>.partition(predicates: List<(T) -> Boolean>): List<List<T>> { | |
val groups = groupBy { item -> predicates.firstMatch(item) } | |
return predicates.map { predicate -> groups.getOrDefault(predicate, emptyList()) } | |
} | |
private fun <T> List<(T) -> Boolean>.firstMatch(item: T) = find { predicate -> predicate(item) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment