Skip to content

Commit 194ed6e

Browse files
Add List.findBy() and reorganize
1 parent 3f3a97b commit 194ed6e

1 file changed

Lines changed: 30 additions & 23 deletions

File tree

src/main/kotlin/KotlinFunctionLibrary.kt

Lines changed: 30 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -801,29 +801,6 @@ println("workingList2=$workingList2")*/
801801
return missingIndices.toList()
802802
}
803803

804-
fun <T> List<T>.indexOf(element: T, startIndex: Int): Int? {
805-
for (i in startIndex until this.size) {
806-
if (this[i] == element) return i
807-
}
808-
return null
809-
}
810-
811-
fun <T> Iterable<T>.toFrequencyMap(): Map<T, Int> {
812-
val frequencies: MutableMap<T, Int> = mutableMapOf()
813-
this.forEach { frequencies[it] = frequencies.getOrDefault(it, 0) + 1 }
814-
return frequencies
815-
}
816-
817-
/**
818-
* Returns a list which contains a copy of [this] [n] times: e.g. listOf(1,2,3).multiplyBy(3){it+1} == listOf(1,2,3, 2,3,4, 2,3,4)
819-
* */
820-
inline fun <E> MutableList<E>.multiplyListBy(n: Int, transform: (E) -> E): MutableList<E> {
821-
return also {
822-
val original = it.toList()
823-
(1 until n).forEach { i -> it.addAll(original.map { it1 -> transform(it1) }) }
824-
}
825-
}
826-
827804
/**
828805
* A small method to do primitive warming up of the JVM.
829806
* */
@@ -912,6 +889,36 @@ println("workingList2=$workingList2")*/
912889
return -1
913890
}
914891

892+
fun <T> List<T>.indexOf(element: T, startIndex: Int): Int? {
893+
for (i in startIndex until this.size) { //TODO use subList()?
894+
if (this[i] == element) return i
895+
}
896+
return null
897+
}
898+
899+
fun <T> Iterable<T>.toFrequencyMap(): Map<T, Int> {
900+
val frequencies: MutableMap<T, Int> = mutableMapOf()
901+
this.forEach { frequencies[it] = frequencies.getOrDefault(it, 0) + 1 }
902+
return frequencies
903+
}
904+
905+
/**
906+
* Returns a list which contains a copy of [this] [n] times: e.g. listOf(1,2,3).multiplyBy(3){it+1} == listOf(1,2,3, 2,3,4, 2,3,4)
907+
* */
908+
inline fun <E> MutableList<E>.multiplyListBy(n: Int, transform: (E) -> E): MutableList<E> {
909+
return also {
910+
val original = it.toList()
911+
(1 until n).forEach { i -> it.addAll(original.map { it1 -> transform(it1) }) }
912+
}
913+
}
914+
/**
915+
* A wrapper around [Iterable.find] which simplifies looking for a specific element by one of its properties.
916+
* Similar to [Iterable.maxBy], but with a specific object in mind.
917+
* @sample listOf<Foo>(...).findBy(bar) { it.bar }
918+
* */
919+
fun <T, R> Iterable<T>.findBy(key: R, selector: (T) -> R): T? = find { selector(it) == key }
920+
921+
915922
/**
916923
* Splits a list by a predicate. List analog to [String.split]
917924
* */

0 commit comments

Comments
 (0)