Refactor finding needles to be better readable
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / web / pages / SearchPage.kt
index d021dfb..69b7c85 100644 (file)
@@ -43,7 +43,7 @@ class SearchPage @JvmOverloads constructor(template: Template, webInterface: Web
                        1 -> phrases.first().phrase.also { word ->
                                when {
                                        word.removePrefix("sone://").let(webInterface.core::getSone) != null -> redirect("viewSone.html?sone=${word.removePrefix("sone://")}")
-                                       word.removePrefix("post://").let(webInterface.core::getPost).isPresent -> redirect("viewPost.html?post=${word.removePrefix("post://")}")
+                                       word.removePrefix("post://").let(webInterface.core::getPost) != null -> redirect("viewPost.html?post=${word.removePrefix("post://")}")
                                        word.removePrefix("reply://").let(webInterface.core::getPostReply) != null -> redirect("viewPost.html?post=${word.removePrefix("reply://").let(webInterface.core::getPostReply)?.postId}")
                                        word.removePrefix("album://").let(webInterface.core::getAlbum) != null -> redirect("imageBrowser.html?album=${word.removePrefix("album://")}")
                                        word.removePrefix("image://").let { webInterface.core.getImage(it, false) } != null -> redirect("imageBrowser.html?image=${word.removePrefix("image://")}")
@@ -106,15 +106,12 @@ class SearchPage @JvmOverloads constructor(template: Template, webInterface: Web
                return requiredHits * 3 + optionalHits + (requiredHits - requiredPhrases) * 5 - (forbiddenHits * 2)
        }
 
-       private fun String.findAll(needle: String): List<Int> {
-               var nextIndex = indexOf(needle)
-               val positions = mutableListOf<Int>()
-               while (nextIndex != -1) {
-                       positions += nextIndex
-                       nextIndex = indexOf(needle, nextIndex + 1)
-               }
-               return positions
-       }
+       private fun String.findAll(needle: String) =
+                       generateSequence(indexOf(needle).takeIf { it > -1 }) { lastPosition ->
+                               lastPosition
+                                               .let { indexOf(needle, it + 1) }
+                                               .takeIf { it > -1 }
+                       }.toList()
 
        private fun String.parse() =
                        StringEscaper.parseLine(this)