Created
April 27, 2025 01:44
-
-
Save sarasfox/685fdcbeec42c7db3e36bf72f27afe12 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import gleam/dynamic/decode | |
import gleam/json | |
import gleam/list | |
import gleam/dict | |
pub type InitCharacter { | |
InitCharacter( | |
name: String, | |
stats: List(#(String, Int)), | |
pools: List(#(String, Int)), | |
) | |
} | |
pub fn serialize_init_character(character: InitCharacter) -> String { | |
let stats = | |
character.stats | |
|> list.map(fn(stat) { json.object([#(stat.0, json.int(stat.1))]) }) | |
let pools = | |
character.pools | |
|> list.map(fn(pool) { json.object([#(pool.0, json.int(pool.1))]) }) | |
json.object([ | |
#("name", json.string(character.name)), | |
#("stats", json.array(stats, fn(stat) { stat })), | |
#("pools", json.array(pools, fn(pool) { pool })), | |
]) | |
|> json.to_string | |
} | |
pub fn deserialize_init_character( | |
json_string: String, | |
) -> Result(InitCharacter, json.DecodeError) { | |
let char_decoder = { | |
use name <- decode.field("name", decode.string) | |
use stats <- decode.field("stats", decode.list(decode.dict(decode.string, decode.int))) | |
use pools <- decode.field("pools", decode.list(decode.dict(decode.string, decode.int))) | |
decode.success(InitCharacter( | |
name: name, | |
stats: stats |> list.map(fn(dict) { | |
case dict.to_list(dict) { | |
[pair] -> pair | |
_ -> #("", 0) | |
} | |
}), | |
pools: pools |> list.map(fn(dict) { | |
case dict.to_list(dict) { | |
[pair] -> pair | |
_ -> #("", 0) | |
} | |
}) | |
)) | |
} | |
json.parse(from: json_string, using: char_decoder) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment