Skip to content

Commit

Permalink
feat: AddOrReplace collection method
Browse files Browse the repository at this point in the history
  • Loading branch information
pkeefe committed Oct 28, 2018
1 parent cb9ed66 commit d1fa42d
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions library/src/main/java/com/perculacreative/ktx/Collection.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ fun <T> MutableCollection<T>.replaceWith(collection: Collection<T>) {
addAll(collection)
}

/**
* Replaces the first item within the list that matches the given predicate or adds the item to
* the list if none match.
*/
fun <T> MutableList<T>.addOrReplace(item: T, predicate: (T) -> Boolean): Boolean {
return this.indexOfFirst { predicate.invoke(it) }
.takeIf { it >= 0 }
?.let { this[it] = item }
?.let { true }
?: this.add(item)
.let { false }
}

fun <S: MutableList<T>, T> S.addAnd(index: Int, item: T): S {
add(index, item)
return this
Expand Down

0 comments on commit d1fa42d

Please sign in to comment.