Skip to content

Commit

Permalink
Add convenience Collections.contains fun that takes a Predicate param
Browse files Browse the repository at this point in the history
  • Loading branch information
janseeger committed Nov 12, 2024
1 parent 1805333 commit 74643c6
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package de.sipgate.dachlatten.primitives

import de.sipgate.dachlatten.primitives.predicates.Predicate

fun <T> Collection<T>.contains(predicate: Predicate<T>): Boolean {
return firstOrNull { predicate(it) } != null
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package de.sipgate.dachlatten.primitives

import de.sipgate.dachlatten.primitives.predicates.Predicate
import de.sipgate.dachlatten.primitives.predicates.not
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class ComplexContainsTest {

val list = listOf("a1entry", "b2entry", "otherEntry")

@Test
fun testSimpleContains() = runTest {
val result = list.contains<String> { it == "a1entry" }
assertTrue(result)
}

@Test
fun testSimpleContainsNegative() = runTest {
val result = list.contains<String> { it == "does-not-exist" }
assertFalse(result)
}

@Test
fun testComplexContains() = runTest {
val result = list.contains<String> { it.all { it.isLetter() } }
assertTrue(result)
}

@Test
fun testComplexContainsNegative() = runTest {
val result = list.contains<String> { it.all { it.isWhitespace() } }
assertFalse(result)
}

@Test
fun testComplexContainsInvert() = runTest {
val complexPredicate: Predicate<String> = { it.all { it.isWhitespace() } }
val invertedPredicate = !complexPredicate
val result = list.contains<String>(invertedPredicate)
assertTrue(result)
}
}

0 comments on commit 74643c6

Please sign in to comment.