From d1fa42d8aa9bae3a32f586f4da923fbf5468237d Mon Sep 17 00:00:00 2001 From: pkeefe Date: Sun, 28 Oct 2018 08:54:43 -0400 Subject: [PATCH] feat: AddOrReplace collection method --- .../main/java/com/perculacreative/ktx/Collection.kt | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/library/src/main/java/com/perculacreative/ktx/Collection.kt b/library/src/main/java/com/perculacreative/ktx/Collection.kt index 9b8a370..3f34541 100644 --- a/library/src/main/java/com/perculacreative/ktx/Collection.kt +++ b/library/src/main/java/com/perculacreative/ktx/Collection.kt @@ -28,6 +28,19 @@ fun MutableCollection.replaceWith(collection: Collection) { 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 MutableList.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 , T> S.addAnd(index: Int, item: T): S { add(index, item) return this