-
Notifications
You must be signed in to change notification settings - Fork 94
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2fcc0e0
commit a16cde2
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
/* | ||
* ShortURL (https://github.com/delight-im/ShortURL) | ||
* Copyright (c) delight.im (https://www.delight.im/) | ||
* Licensed under the MIT License (https://opensource.org/licenses/MIT) | ||
*/ | ||
|
||
/** | ||
* ShortURL: Bijective conversion between natural numbers (IDs) and short strings | ||
* | ||
* ShortURL.encode() takes an ID and turns it into a short string | ||
* ShortURL.decode() takes a short string and turns it into an ID | ||
* | ||
* Features: | ||
* + large alphabet (51 chars) and thus very short resulting strings | ||
* + proof against offensive words (removed 'a', 'e', 'i', 'o' and 'u') | ||
* + unambiguous (removed 'I', 'l', '1', 'O' and '0') | ||
* | ||
* Example output: | ||
* 123456789 <=> pgK8p | ||
*/ | ||
object ShortURL { | ||
|
||
private val ALPHABET = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_" | ||
private val BASE = ALPHABET.length | ||
|
||
fun encode(num: Int): String { | ||
var number = num | ||
val stringBuilder = StringBuilder() | ||
while (number > 0) { | ||
stringBuilder.insert(0, ALPHABET[number % BASE]) | ||
number /= BASE | ||
} | ||
|
||
return stringBuilder.toString() | ||
} | ||
|
||
fun decode(string: String): Int { | ||
var number = 0 | ||
for (i in 0 until string.length) { | ||
number = number * BASE + ALPHABET.indexOf(string[i]) | ||
} | ||
|
||
return number | ||
} | ||
|
||
} |