kotovalexarian
/
android
Archived
1
0
Fork 0

Add class ArticleId

This commit is contained in:
Alex Kotov 2021-08-16 04:22:00 +05:00
parent e1b34b1d7e
commit a73913bdb4
Signed by: kotovalexarian
GPG Key ID: 553C0EBBEB5D5F08
2 changed files with 48 additions and 7 deletions

View File

@ -0,0 +1,36 @@
package com.causa_arcana
import java.lang.RuntimeException
class ArticleId(val year: UInt, val month: UInt, val day: UInt, val slug: String) {
init {
if (year !in 2000u..3000u) throw RuntimeException("Invalid article year")
if (month !in 1u..12u) throw RuntimeException("Invalid article month")
if (day !in 1u..31u) throw RuntimeException("Invalid article day")
if (!SLUG_RE.matches(slug)) throw RuntimeException("Invalid article slug")
}
override fun toString(): String {
return "${yearPadded()}-${monthPadded()}-${dayPadded()}-$slug"
}
private fun yearPadded(): String = year .toString().padStart(4, '0')
private fun monthPadded(): String = month.toString().padStart(2, '0')
private fun dayPadded(): String = day .toString().padStart(2, '0')
companion object {
private val ID_RE = """^(\d{4})-(\d\d)-(\d\d)-([a-z0-9]+)(-[a-z0-9]+)*$""".toRegex()
private val SLUG_RE = """^([a-z0-9]+)(-[a-z0-9]+)*$""".toRegex()
fun fromString(id: String): ArticleId {
(ID_RE.matchEntire(id) ?: throw RuntimeException("Invalid article ID")).destructured
.let { (year, month, day, slugHead, slugTail) -> return ArticleId(
year.toUInt(),
month.toUInt(),
day.toUInt(),
slugHead + slugTail,
)
}
}
}
}

View File

@ -4,14 +4,19 @@ import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
fun articleIdFromString() {
val articleId = ArticleId.fromString("2021-01-01-hello-world")
assertEquals(2021u, articleId.year)
assertEquals(1u, articleId.month)
assertEquals(1u, articleId.day)
assertEquals("hello-world", articleId.slug)
}
@Test
fun articleIdToString() {
val articleId = ArticleId(2021u, 1u, 1u, "hello-world")
assertEquals("2021-01-01-hello-world", articleId.toString())
}
}