Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using Kotlin require function to check for number range and maximum attempts #3

Merged
merged 2 commits into from
Dec 31, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
}
}