From 1f67b80aea57a5148b636b9266bfbf5b3d1e8f7b Mon Sep 17 00:00:00 2001 From: Andrei Mukamolau <4471821+fobo66@users.noreply.github.com> Date: Sat, 11 Jan 2025 22:59:17 +0200 Subject: [PATCH] Added experimental extensions to switch to androidx.collections during mapping --- .../core/util/ScatterSetExtensions.kt | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 data/src/main/kotlin/fobo66/valiutchik/core/util/ScatterSetExtensions.kt diff --git a/data/src/main/kotlin/fobo66/valiutchik/core/util/ScatterSetExtensions.kt b/data/src/main/kotlin/fobo66/valiutchik/core/util/ScatterSetExtensions.kt new file mode 100644 index 00000000..ed32a626 --- /dev/null +++ b/data/src/main/kotlin/fobo66/valiutchik/core/util/ScatterSetExtensions.kt @@ -0,0 +1,44 @@ +/* + * Copyright 2025 Andrey Mukamolov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package fobo66.valiutchik.core.util + +import androidx.collection.MutableScatterMap +import androidx.collection.ScatterMap +import androidx.collection.ScatterSet + +@SinceKotlin("1.3") +inline fun ScatterSet.associateWith(valueSelector: (K) -> V): ScatterMap { + val result = MutableScatterMap() + return associateWithTo(result, valueSelector) +} + +/** + * Populates and returns the [destination] mutable map with key-value pairs for each element of the given collection, + * where key is the element itself and value is provided by the [valueSelector] function applied to that key. + * + * If any two elements are equal, the last one overwrites the former value in the map. + * + */ +inline fun > ScatterSet.associateWithTo( + destination: M, + valueSelector: (K) -> V, +): M { + this.forEach { element -> + destination.put(element, valueSelector(element)) + } + return destination +}