json-extra icon indicating copy to clipboard operation
json-extra copied to clipboard

dict2 is not tail recursive

Open prasmussen opened this issue 1 year ago • 0 comments

I got the following error when decoding a big data structure:

RangeError: Maximum call stack size exceeded

I'm not sure if this repo is actively maintained so I won't bother creating a PR, but here is a tail recursive version of dict2 if anyone needs it:

dict2 : Decoder comparable -> Decoder v -> Decoder (Dict comparable v)
dict2 keyDecoder valueDecoder =
    Decode.keyValuePairs valueDecoder
        |> Decode.andThen (decodeDictFromTuples keyDecoder)


decodeDictFromTuples : Decoder comparable -> List ( String, v ) -> Decoder (Dict comparable v)
decodeDictFromTuples keyDecoder tuples =
    let
        helper : List ( String, v ) -> Dict comparable v -> Decoder (Dict comparable v)
        helper remainingTuples dictAcc =
            case remainingTuples of
                [] ->
                    Decode.succeed dictAcc

                ( strKey, value ) :: rest ->
                    case Decode.decodeString keyDecoder strKey of
                        Ok key ->
                            helper rest (Dict.insert key value dictAcc)

                        Err error ->
                            Decode.fail (Decode.errorToString error)
    in
    helper tuples Dict.empty

prasmussen avatar Aug 19 '24 08:08 prasmussen