Skip to content

Instantly share code, notes, and snippets.

@mattttvaughn
Created February 23, 2022 01:43
Show Gist options
  • Save mattttvaughn/08514c66f0bf6457564f1e8008e78db7 to your computer and use it in GitHub Desktop.
Save mattttvaughn/08514c66f0bf6457564f1e8008e78db7 to your computer and use it in GitHub Desktop.
Sample tests for TitleSortComparator
package io.github.mattpvaughn.chronicle.features.library
// src/main/java/io/github/mattpvaughn/chronicle/features/library/TitleSortComparator.kt
/** Compares Book titles using numerical ordering */
class TitleSortComparator {
fun compare(bookTitle1: String, bookTitle2: String): Int {
fun titleToArray(bookTitle: String): List<String> {
return bookTitle.split(Regex("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"))
}
val title1: Iterator<String> = titleToArray(bookTitle1).iterator()
val title2: Iterator<String> = titleToArray(bookTitle2).iterator()
while (true) {
val bool1: Boolean = title1.hasNext()
val bool2: Boolean = title2.hasNext()
if (!(bool1 || bool2)) {
return 0
}
if (!bool1) return -1
if (!bool2) return 1
val next1: String = title1.next()
val next2: String = title2.next()
try {
if (next1.toInt() > next2.toInt())
return 1
else if (next1.toInt() < next2.toInt())
return -1
} catch (e: NumberFormatException) {
val comp: Int = next1.compareTo(next2)
if (comp != 0) return comp
}
}
}
}
package io.github.mattpvaughn.chronicle.features.library
import org.junit.Assert.assertEquals
import org.junit.Test
// src/test/java/io/github/mattpvaughn/chronicle/features/library/TitleSortComparatorTest.kt
class TitleSortComparatorTest {
private val titleSortComparator = TitleSortComparator()
@Test
fun `lower digit comes before higher digit`() {
"1".assertComesBefore("2")
}
@Test
fun `lower character comes before higher character`() {
"a".assertComesBefore("b")
}
private fun String.assertComesBefore(other: String) {
assertEquals(
-1,
titleSortComparator.compare(this, other)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment