Skip to content

Commit d1571ac

Browse files
refactor: Optimize list sorting and indexing logic
This commit refactors the list processing logic to improve its efficiency and safety. Previously, sorting involved multiple index lookups (`list.indexOf(it)`) within the comparator, which was inefficient. The new implementation pre-calculates the pinned status of each item and stores it in a `pinnedStatusMap`. This map is then used during the sorting process, eliminating the need for repeated index lookups. Additionally, building the scroll index has been made safer by using the `pinnedStatusMap` instead of relying on `items.getOrNull(index)`, avoiding potential mismatches. The comments in the code have also been updated to reflect these changes.
1 parent c823cd1 commit d1571ac

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

app/src/main/java/com/github/droidworksstudio/mlauncher/MainViewModel.kt

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -463,26 +463,29 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
463463
val list = mutableListOf<R>()
464464
val scrollMap = mutableMapOf<String, Int>()
465465

466-
// ✅ Filter and build list
466+
// Build the visible list
467467
items.forEach { raw ->
468468
val key = getKey(raw)
469469
if (!seenKey.add(key)) return@forEach
470470
if (isHidden(raw) && !includeHidden) return@forEach
471471
list.add(buildItem(raw))
472472
}
473473

474-
val pinnedMap = items.associateWith { isPinned(it) } // Map<T, Boolean>
474+
// Build a map between built items and their pinned status
475+
val pinnedStatusMap = items.zip(list).associate { (item, built) ->
476+
built to isPinned(item)
477+
}
475478

476-
// Sort pinned first, then by normalized label
479+
// Sort safely: no index lookups during sorting
477480
list.sortWith(
478-
compareByDescending<R> { pinnedMap[items[list.indexOf(it)]] == true }
481+
compareByDescending<R> { pinnedStatusMap[it] == true }
479482
.thenBy { normalize(getLabel(it)) }
480483
)
481484

482-
// Build scroll index (safe, no `continue`)
485+
// Build scroll index
483486
list.forEachIndexed { index, item ->
484487
val label = getLabel(item)
485-
val pinned = items.getOrNull(index)?.let(isPinned) == true
488+
val pinned = pinnedStatusMap[item] == true
486489
val key = if (pinned) "" else label.firstOrNull()?.uppercaseChar()?.toString() ?: "#"
487490
scrollMap.putIfAbsent(key, index)
488491
}

0 commit comments

Comments
 (0)