Skip to content

Commit

Permalink
feat(field): add replaceMatching method replacing the values in a f…
Browse files Browse the repository at this point in the history
…ield matching a given predicate (#550)
  • Loading branch information
nicolasfara authored Nov 7, 2024
1 parent 1f4a8c9 commit ca768d0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,19 @@ inline fun <ID : Any, T> Field<ID, T>.none(crossinline predicate: (T) -> Boolean
*/
inline fun <ID : Any, T> Field<ID, T>.noneWithSelf(crossinline predicate: (T) -> Boolean): Boolean =
!anyWithSelf(predicate)

/**
* Returns a new field containing [replaceWith] for each element that satisfies the [predicate].
*/
inline fun <ID : Any, T> Field<ID, T>.replaceMatchingWithId(
replaceWith: T,
crossinline predicate: (ID, T) -> Boolean,
): Field<ID, T> = mapWithId { id, value -> if (predicate(id, value)) replaceWith else value }

/**
* Returns a new field containing [replaceWith] for each element that satisfies the [predicate].
*/
inline fun <ID : Any, T> Field<ID, T>.replaceMatching(
replaceWith: T,
crossinline predicate: (T) -> Boolean,
): Field<ID, T> = replaceMatchingWithId(replaceWith) { _, value -> predicate(value) }
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import it.unibo.collektive.field.Field.Companion.fold
import it.unibo.collektive.field.Field.Companion.foldWithId
import it.unibo.collektive.field.Field.Companion.hood
import it.unibo.collektive.field.Field.Companion.hoodWithId
import it.unibo.collektive.field.operations.replaceMatching

class FieldOpsTest : StringSpec({
val emptyField = Field(0, "localVal")
Expand Down Expand Up @@ -71,4 +72,13 @@ class FieldOpsTest : StringSpec({
field.asSequence().toList() shouldContainAll
sequenceOf(0 to 0, 1 to 10, 2 to 20).toList()
}
"The replaceMatching on an empty field should return an empty field" {
emptyField.replaceMatching("replaced") { it == "no-data" } shouldBe emptyField
}
"The replaceMatching should return the same field if the predicate is not satisfied" {
field.replaceMatching(Int.MAX_VALUE) { it == 42 } shouldBe field
}
"The replaceMatching should return a field with the replaced values" {
field.replaceMatching(42) { it == 10 } shouldBe Field(0, 0, mapOf(1 to 42, 2 to 20))
}
})

0 comments on commit ca768d0

Please sign in to comment.