Skip to content

Commit

Permalink
Merge pull request #3 from jelle82/Builtin-require
Browse files Browse the repository at this point in the history
Using Kotlin require function to check for number range and maximum attempts
  • Loading branch information
kevinxmorales authored Dec 31, 2023
2 parents 2693249 + 3046006 commit a2741e1
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/main/kotlin/org/sqidskotlin/sqids/Sqids.kt
Original file line number Diff line number Diff line change
Expand Up @@ -653,15 +653,15 @@ class Sqids(private var alphabet: String = DEFAULT_ALPHABET, private val minLeng
* - An n-number of attempts has been made to re-generated the ID, where n is alphabet length + 1
*
* @return the generated ID
* @throws IllegalArgumentException if one of the numbers passed is smaller than 0 or greater than `maxValue()`
* @throws IllegalStateException if n attempts have been made to re-generated the ID, where n is alphabet length + 1
*/
fun encode(numbers: List<Long>): String {
if (numbers.isEmpty()) {
return ""
}
val inRangeNumbers = numbers.filter { n -> n >= 0 }
if(inRangeNumbers.size != numbers.size) {
throw RuntimeException("Encoding supports numbers between 0 and " + Long.MAX_VALUE)
}

require(numbers.all { it >= 0 }) { "Encoding supports numbers between 0 and ${Long.MAX_VALUE}" }
return encodeNumbers(numbers)
}

Expand All @@ -672,9 +672,8 @@ class Sqids(private var alphabet: String = DEFAULT_ALPHABET, private val minLeng
* @return the generated ID
*/
private fun encodeNumbers(numbers: List<Long>, increment: Int = 0): String {
if (increment > alphabet.length) {
throw RuntimeException("Reached max attempts to re-generate the ID")
}

check(increment <= alphabet.length) { "Reached max attempts to re-generate the ID" }

var offset = numbers.size
for (i in numbers.indices) {
Expand Down Expand Up @@ -758,4 +757,4 @@ class Sqids(private var alphabet: String = DEFAULT_ALPHABET, private val minLeng
}
return false
}
}
}

0 comments on commit a2741e1

Please sign in to comment.