Skip to content

Commit 652a993

Browse files
krisajenkinsshmish111
authored andcommitted
Adding encoders/decoders for Either.
1 parent 961aa70 commit 652a993

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

src/Foreign/Generic/Class.purs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,12 @@ instance setDecode :: (Ord a, Decode a) => Decode (Set a) where
198198
(arr :: Array a) <- decode f
199199
pure $ Set.fromFoldable arr
200200

201+
instance eitherDecode :: (Decode a, Decode b) => Decode (Either a b) where
202+
decode value =
203+
(readProp "Left" value >>= (map Left <<< decode))
204+
<|>
205+
(readProp "Right" value >>= (map Right <<< decode))
206+
201207
-- | The `Encode` class is used to generate encoding functions
202208
-- | of the form `a -> Foreign` using `generics-rep` deriving.
203209
-- |
@@ -267,6 +273,11 @@ instance mapEncode :: (Encode k, Encode v) => Encode (Map k v) where
267273
instance setEncode :: (Ord a, Encode a) => Encode (Set a) where
268274
encode s = let (arr :: Array a) = Set.toUnfoldable s in encode arr
269275

276+
277+
instance encodeEither :: (Encode a, Encode b) => Encode (Either a b) where
278+
encode (Left a) = encode $ Object.singleton "Left" a
279+
encode (Right b) = encode $ Object.singleton "Right" b
280+
270281
-- | When deriving `En`/`Decode` instances using `Generic`, we want
271282
-- | the `Options` object to apply to the outermost record type(s)
272283
-- | under the data constructors.

test/Main.purs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@ main = do
140140
testRoundTrip (makeTree 5)
141141
testRoundTrip (Object.fromFoldable [Tuple "one" 1, Tuple "two" 2])
142142
testRoundTrip (Map.fromFoldable [Tuple "one" 1, Tuple "two" 2])
143+
testRoundTrip [ Left 5, Right "Test" ]
143144
testUnaryConstructorLiteral
144145
let opts = defaultOptions { fieldTransform = toUpper }
145146
testGenericRoundTrip opts (RecordTest { foo: 1, bar: "test", baz: 'a' })

0 commit comments

Comments
 (0)