Skip to content

Commit d8ac7f7

Browse files
committed
Add encode and decode instance for Set
1 parent 1cb9de6 commit d8ac7f7

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/Foreign/Generic/Class.purs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ module Foreign.Generic.Class where
33
import Prelude
44

55
import Control.Alt ((<|>))
6+
import Control.Bind (bindFlipped)
67
import Control.Monad.Except (except, mapExcept)
78
import Data.Array ((..), zipWith, length)
89
import Data.Bifunctor (lmap)
@@ -14,6 +15,8 @@ import Data.List (List(..), (:))
1415
import Data.List as List
1516
import Data.Maybe (Maybe(..), maybe)
1617
import Data.Newtype (unwrap)
18+
import Data.Set (Set)
19+
import Data.Set as Set
1720
import Data.Symbol (class IsSymbol, SProxy(..), reflectSymbol)
1821
import Data.Traversable (sequence)
1922
import Data.Tuple (Tuple(..))
@@ -135,6 +138,15 @@ instance arrayDecode :: Decode a => Decode (Array a) where
135138
readElement :: Int -> Foreign -> F a
136139
readElement i value = mapExcept (lmap (map (ErrorAtIndex i))) (decode value)
137140

141+
instance setDecode :: (Decode a, Ord a) => Decode (Set a) where
142+
decode = (decode :: _ -> F (Array a)) >>> bindFlipped arrayToSetNoDuplicates
143+
where
144+
arrayToSetNoDuplicates :: Array a -> F (Set a)
145+
arrayToSetNoDuplicates array = case Set.fromFoldable array of
146+
set
147+
| length array == Set.size set -> pure set
148+
_ -> except $ Left $ pure $ ForeignError "Decode set: The foreign value contains duplicates"
149+
138150
instance maybeDecode :: Decode a => Decode (Maybe a) where
139151
decode = readNullOrUndefined decode
140152

@@ -192,6 +204,9 @@ instance identityEncode :: Encode a => Encode (Identity a) where
192204
instance arrayEncode :: Encode a => Encode (Array a) where
193205
encode = unsafeToForeign <<< map encode
194206

207+
instance setEncode :: (Encode a, Ord a) => Encode (Set a) where
208+
encode = (Set.toUnfoldable :: Set a -> Array a) >>> encode
209+
195210
instance maybeEncode :: Encode a => Encode (Maybe a) where
196211
encode = maybe null encode
197212

0 commit comments

Comments
 (0)