Skip to content

Commit

Permalink
✨ IdGenerator can have random overridden
Browse files Browse the repository at this point in the history
  • Loading branch information
oharaandrew314 committed Feb 3, 2024
1 parent 83a1e0e commit 18933ec
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/main/kotlin/io/andrewohara/utils/IdGenerator.kt
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package io.andrewohara.utils

import java.security.SecureRandom
import java.util.Random

object IdGenerator {
open class IdGenerator(private val random: Random = Random()) {

companion object: IdGenerator()

private val base36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray()
private val numeric = "0123456789".toCharArray()
private val hex = "0123456789abcdef".toCharArray()
private val random = SecureRandom()
private val hex = "0123456789ABCDEF".toCharArray()

private fun next(length: Int, chars: CharArray): String {
val sb = StringBuilder(length)
Expand All @@ -21,5 +22,5 @@ object IdGenerator {

fun nextNumeric(length: Int) = next(length, numeric).toBigInteger()

fun nextHex(length: Int) = next(length, hex).lowercase()
fun nextHex(length: Int) = next(length, hex)
}
33 changes: 33 additions & 0 deletions src/test/kotlin/io/andrewohara/utils/IdGeneratorTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package io.andrewohara.utils

import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldHaveLength
import org.junit.jupiter.api.Test
import java.util.Random

class IdGeneratorTest {

private val testObj = IdGenerator(Random(1337))

@Test
fun `next hex`() {
testObj.nextHex(8) shouldBe "19E79D84"
}

@Test
fun `next base36`() {
testObj.nextBase36(8) shouldBe "QETRJ88E"
}

@Test
fun `next numeric`() {
testObj.nextNumeric(8) shouldBe 10546784.toBigInteger()
}

@Test
fun `companion object`() {
IdGenerator.nextHex(4).shouldHaveLength(4)
IdGenerator.nextNumeric(4).toString().shouldHaveLength(4)
IdGenerator.nextBase36(4).shouldHaveLength(4)
}
}

0 comments on commit 18933ec

Please sign in to comment.