Skip to content

Commit

Permalink
refactor: remove list.at
Browse files Browse the repository at this point in the history
  • Loading branch information
okkdev committed Jun 4, 2024
1 parent 0fa399a commit 2bb0436
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/ids/base32.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,21 @@ import gleam/string
/// Used by ULID and TypeID
@internal
pub fn encode(bytes: BitArray, alphabet: String) -> String {
let alphabet_with_index =
alphabet
|> string.to_graphemes
|> list.index_map(fn(x, i) { #(i, x) })

// pad 2 bits because we only supply 128 bits of data but need 130 bits for encoding
encode_bytes(<<0:size(2), bytes:bits>>, alphabet)
encode_bytes(<<0:size(2), bytes:bits>>, alphabet_with_index)
}

/// Recursively grabs 5 bits and uses them as index in the alphabet and concatinates them to a string.
fn encode_bytes(binary: BitArray, alphabet: String) -> String {
fn encode_bytes(binary: BitArray, alphabet: List(#(Int, String))) -> String {
case binary {
<<index:unsigned-size(5), rest:bits>> -> {
alphabet
|> string.to_graphemes
|> list.at(index)
|> list.key_find(index)
|> result.unwrap("0")
|> string.append(encode_bytes(rest, alphabet))
}
Expand Down

0 comments on commit 2bb0436

Please sign in to comment.