Created
January 20, 2015 20:28
-
-
Save benkolera/6a3622aa5c6ceb99dcf8 to your computer and use it in GitHub Desktop.
Potential tidy of answer here: http://stackoverflow.com/questions/27885264/creating-purescript-records-from-inconsistent-javascript-objects/28042483#28042483
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
hush :: Either e a -> Maybe a | |
hush = either (const Nothing) Just | |
toId :: JObject -> Maybe Number | |
toId o = fromNumber <|> fromString | |
where | |
fromNumber = hush $ o .? "id" | |
fromString = do | |
s <- hush $ o .? "id" | |
mfilter (isNan >>> not) Just (readFloat s) | |
toUsername :: JObject -> Maybe String | |
toUsername o = hush $ o .? "username" | |
toEmail :: Json -> Maybe String | |
toEmail o = hush $ o .? "email" | |
toIsActive :: Json -> Maybe Boolean | |
toIsActive o = either (const (Just true)) Just $ o .? "isActive" | |
toUser :: Json -> Maybe User | |
toUser json = do | |
obj <- toObject | |
id <- toId obj | |
username <- toUsername obj | |
isActive <- toIsActive obj | |
return { id: id | |
, username: username | |
, email: toEmail json | |
, isActive: isActive | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!
hush
improves readability significantly. I've incorporated your improvements into my answer.