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

Add Json.Encode.Extra.at counterpart to Json.Decode.at #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

choonkeat
Copy link

The standard elm/json has a nice function Json.Decode.at

Json.Decode.at [ "Nightmare", "At" ] Json.Decode.string

This PR introduces the counterpart for encoding: Json.Encode.Extra.at

encodedValue = (Json.Encode.string "Elm Street")

Json.Encode.Extra.at [ "Nightmare", "At" ] encodedValue
-- {"Nightmare":{"At":"Elm Street"}}

@zwilias
Copy link
Member

zwilias commented Dec 6, 2019

Cool!

How would you feel about taking the "encoder" and the "value to be encoded" both as arguments, much in the same way Encode.list takes an a -> Encode.Value and a List a?

So, the result would be something like

at : List String -> (a -> Encode.Value) -> a -> Encode.Value
at path enc val = List.foldr (\x acc -> Encode.object [ (x, acc) ]) (enc val) path

Which would turn the example into at [ "Nightmare", "at" ] Encode.string "Elm Street"

@choonkeat
Copy link
Author

choonkeat commented Dec 6, 2019

Oh foldr is much better!

As for arguments, in scenarios where I have encoder & value, I could use either api inline: wrapping in parentheses for the first api.

at [ "Nightmare", "at" ] Encode.string "Elm Street"
at [ "Nightmare", "at" ] (Encode.string "Elm Street")

But if I only have an encodedValue, I’d need to pass identity into the 2nd api, a bit more unnatural?

at [ "Nightmare", "at" ] identity encodedValue
at [ "Nightmare", "at" ] encodedValue

counterpart to Json.Decode.at
@choonkeat
Copy link
Author

  • updated to use foldr 🙇
  • avoided point free style since current argument order more intuitive and matches Decode.at

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

Successfully merging this pull request may close these issues.

2 participants