Zyle Moore
05/09/2024, 12:32 AMinline fun ByteArray.indicesOf(value: Byte): List<Int> =
mapIndexed { index, byte -> index.takeIf { byte == value } }.filterNotNull()
Zyle Moore
05/09/2024, 12:33 AMephemient
05/09/2024, 2:07 AMmapIndexedNotNull
Zyle Moore
05/09/2024, 2:15 AMZyle Moore
05/09/2024, 2:16 AMZyle Moore
05/09/2024, 2:18 AMtoTypedArray().mapIndexedNotNull { index, byte -> index.takeIf { byte == value } }
ephemient
05/09/2024, 2:20 AMephemient
05/09/2024, 2:21 AMinline fun ByteArray.indicesOf(value: Byte): List<Int> = buildList {
for ((index, byte) in this@indicesOf.withIndex()) {
if (byte == value) add(index)
}
}
to be clearerYoussef Shoaib [MOD]
05/09/2024, 3:14 AMforEachIndexed
there just because it doesn't allocate the IndexedValue, but it really doesn't matterKlitos Kyriacou
05/09/2024, 9:34 AMfun ByteArray.indicesOf(value: Byte): List<Int> =
withIndex().mapNotNull { (index, byte) -> index.takeIf { byte == value } }
This is as short as the above solutions that use mapIndexed
and mapIndexedNotNull
but it doesn't create an intermediate list, since withIndex
returns a lazy iterator.
Also, the following doesn't create any copies of the data, but just a list wrapping the original array:
asList().mapIndexedNotNull { index, byte -> index.takeIf { byte == value } }
which is exactly like your solution that uses toTypedArray
but without copying the data.ephemient
05/09/2024, 1:27 PMbecause it doesn't allocate the IndexedValue
for (.withIndex())
is intrinsified so it doesn't either, https://youtrack.jetbrains.com/issue/KT-5177/Optimize-code-generation-for-for-loop-with-withIndexKlitos Kyriacou
05/09/2024, 1:41 PMwithIndex
, since that's where developers would look if they wanted to know more about it, rather than checking old feature requests on YouTrack.ephemient
05/09/2024, 1:47 PM