Created
October 8, 2020 21:37
-
-
Save ream88/af79714140a92472ff6d654c72bc730b to your computer and use it in GitHub Desktop.
ShortUUID decode and encode in Elm
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
module ShortUUID exposing (decode, encode) | |
import BigInt exposing (BigInt) | |
import List.Extra as List | |
import String.Extra as String | |
abc : List Char | |
abc = | |
[ '1', '2', '3', '4', '5', '6', '7', '8', '9' ] | |
++ [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] | |
++ [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ] | |
abcLength : BigInt | |
abcLength = | |
abc |> List.length |> BigInt.fromInt | |
zero : BigInt | |
zero = | |
BigInt.fromInt 0 | |
encode : String -> String | |
encode input = | |
input | |
|> String.replace "-" "" | |
|> BigInt.fromHexString | |
|> Maybe.map (encodeHelper "") | |
|> Maybe.withDefault "" | |
encodeHelper : String -> BigInt -> String | |
encodeHelper output input = | |
if BigInt.gt input zero then | |
let | |
index = | |
input | |
|> BigInt.modBy abcLength | |
|> Maybe.map BigInt.toString | |
|> Maybe.andThen String.toInt | |
|> Maybe.withDefault 0 | |
char = | |
abc | |
|> List.getAt index | |
|> Maybe.withDefault ' ' | |
newInput = | |
BigInt.div input abcLength | |
newOutput = | |
String.cons char output | |
in | |
encodeHelper newOutput newInput | |
else | |
output | |
decode : String -> String | |
decode input = | |
input | |
|> String.toList | |
|> List.foldl | |
(\char acc -> | |
let | |
index = | |
abc | |
|> List.findIndex (\current -> current == char) | |
|> Maybe.withDefault 0 | |
|> BigInt.fromInt | |
in | |
acc | |
|> BigInt.mul abcLength | |
|> BigInt.add index | |
) | |
zero | |
|> BigInt.toHexString | |
|> String.padLeft 32 '0' | |
|> String.insertAt "-" 8 | |
|> String.insertAt "-" 13 | |
|> String.insertAt "-" 18 | |
|> String.insertAt "-" 23 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment