aboutsummaryrefslogtreecommitdiffstats
path: root/style-generator/src/Decoder/Generic.elm
blob: b81167e8b1348339dadc7fbc7471765037eb25a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
module Decoder.Generic exposing (combine, pair, resultToDecoder, subdecode, tail, withDefault)

import Json.Decode as D exposing (Decoder)


withDefault : a -> Decoder a -> Decoder a
withDefault fallback decoder =
    D.oneOf
        [ decoder
        , D.succeed fallback
        ]


combine : List (Decoder a) -> Decoder (List a)
combine =
    List.foldr (D.map2 (::)) (D.succeed [])


subdecode : Decoder a -> D.Value -> Decoder a
subdecode d v =
    D.decodeValue d v |> resultToDecoder


tail : Decoder a -> Decoder (List a)
tail itemDecoder =
    D.list D.value
        |> D.andThen
            (\l ->
                case l of
                    [] ->
                        D.fail "Can't get tail of empty"

                    head :: t ->
                        List.map (subdecode itemDecoder) t |> combine
            )


pair : Decoder a -> Decoder b -> Decoder ( a, b )
pair aDecoder bDecoder =
    D.map2 Tuple.pair
        (D.index 0 aDecoder)
        (D.index 1 bDecoder)


resultToDecoder : Result D.Error a -> Decoder a
resultToDecoder res =
    case res of
        Ok a ->
            D.succeed a

        Err e ->
            D.fail (D.errorToString e)