From 8c69116171117f3ad90f727b4bbdc6a5099feb88 Mon Sep 17 00:00:00 2001 From: Joren Date: Tue, 30 Apr 2024 03:11:29 +0200 Subject: [PATCH] use buildin functions instaid --- .../ui/viewmodels/PokeSearchViewModel.kt | 31 +++++++------------ 1 file changed, 11 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/com/ti/mobpo/ui/viewmodels/PokeSearchViewModel.kt b/app/src/main/java/com/ti/mobpo/ui/viewmodels/PokeSearchViewModel.kt index 404c5a7..f85849e 100644 --- a/app/src/main/java/com/ti/mobpo/ui/viewmodels/PokeSearchViewModel.kt +++ b/app/src/main/java/com/ti/mobpo/ui/viewmodels/PokeSearchViewModel.kt @@ -14,9 +14,9 @@ import kotlinx.coroutines.launch import java.io.IOException -private const val SHOW_LIMIT = 20; +private const val SHOW_LIMIT = 20 class PokeSearchViewModel(private val favouritesRepository: FavouritesRepository) : ViewModel() { - private val service = PokeApi.retrofitService; + private val service = PokeApi.retrofitService private val _pokemonDetails = MutableStateFlow?>(null) val pokemonDetails: StateFlow?> = _pokemonDetails.asStateFlow() @@ -43,10 +43,16 @@ class PokeSearchViewModel(private val favouritesRepository: FavouritesRepository _isLoading.value = true viewModelScope.launch { try { - val filteredList = _initialPokemonList.value?.binarySearch(query) + val firstIndex = _initialPokemonList.value?.indexOfFirst { it.name.startsWith(query, ignoreCase = true) } + val lastIndex = _initialPokemonList.value?.indexOfLast { it.name.startsWith(query, ignoreCase = true) } + val detailsList = mutableListOf() - if (filteredList != null) { - for (index in filteredList until minOf(_initialPokemonList.value?.size ?: 0, filteredList + SHOW_LIMIT)) { + + if (firstIndex != null && lastIndex != null) { + val endIndex = minOf(firstIndex + SHOW_LIMIT, lastIndex + 1) + val startIndex = maxOf(firstIndex, endIndex - SHOW_LIMIT) + + for (index in startIndex until endIndex) { val pokemonSpecies = _initialPokemonList.value!![index] val details = service.getPokemonDetails(extractPokemonId(pokemonSpecies.url)) val isFavorite = favouritesRepository.isFavourite(details.id) @@ -62,21 +68,6 @@ class PokeSearchViewModel(private val favouritesRepository: FavouritesRepository } } - private fun List.binarySearch(query: String): Int { - var low = 0 - var high = this.size - 1 - while (low <= high) { - val mid = (low + high) ushr 1 - val comparison = this[mid].name.compareTo(query, ignoreCase = true) - when { - comparison == 0 -> return mid - comparison < 0 -> low = mid + 1 - else -> high = mid - 1 - } - } - return low - } - private fun extractPokemonId(url: String): Int { val parts = url.split("/") return parts[parts.size - 2].toInt()