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

Support Belt.Map.t #5

Open
ryb73 opened this issue Oct 29, 2018 · 2 comments
Open

Support Belt.Map.t #5

ryb73 opened this issue Oct 29, 2018 · 2 comments

Comments

@ryb73
Copy link
Member

ryb73 commented Oct 29, 2018

No description provided.

@nickretallack
Copy link

Yes, please add this. It's a pretty basic piece of functionality.

Here's how I'm working around it right now for Belt.Map.String.t:

let mapToJson = (encode: 'a => Js.Json.t, map: Belt.Map.String.t('a)) =>
  Json.Encode.object_(
    Belt.List.map(Belt.Map.String.toList(map), ((key, item)) =>
      (key, encode(item))
    ),
  );

let deccoMapFromJson = (decode, json) => {
  switch (Decco.dictFromJson(decode, json)) {
  | Belt.Result.Ok(result) =>
    Ok(Belt.Map.String.fromArray(Js.Dict.entries(result)))
  | Belt.Result.Error(error) => Error(error)
  };
};

[@decco]
type StringMap('a) =
  [@decco.codec (mapToJson, deccoMapFromJson)]
  Belt.Map.String.t('a);

The mapToJson I already had lying around and it happens to work. The other one I had to write custom because decco returns result types while Json.Encode raises exceptions.

@Pet3ris
Copy link

Pet3ris commented Feb 2, 2021

Same idea, applied to integers.

let intMapToJson = (encode: 'a => Js.Json.t, map: Belt.Map.Int.t('a)) =>
  Json.Encode.object_(
    Belt.List.map(Belt.Map.Int.toList(map), ((key, item)) =>
      (string_of_int(key), encode(item))
    ),
  );

let deccoIntMapFromJson = (decode, json) => {
  switch (Decco.dictFromJson(decode, json)) {
  | Belt.Result.Ok(result) =>
    Ok(Js.Dict.entries(result)
    -> Belt.Array.map(((key, value)) => (int_of_string(key), value))
    -> Belt.Map.Int.fromArray)
  | Belt.Result.Error(error) => Error(error)
  };
};

[@decco]
type intMap('a) =
  [@decco.codec (intMapToJson, deccoIntMapFromJson)] Belt.Map.Int.t('a);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants