Add class ArticleId
This commit is contained in:
parent
e1b34b1d7e
commit
a73913bdb4
|
@ -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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -4,14 +4,19 @@ import org.junit.Test
|
||||||
|
|
||||||
import org.junit.Assert.*
|
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 {
|
class ExampleUnitTest {
|
||||||
@Test
|
@Test
|
||||||
fun addition_isCorrect() {
|
fun articleIdFromString() {
|
||||||
assertEquals(4, 2 + 2)
|
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())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Reference in New Issue