-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Description
In the Fluture section, it could be useful to mention Natural Transformation as described in https://github.com/MostlyAdequate/mostly-adequate-guide/blob/master/ch11.md.
I find the following natural transformation of an Either to Future very useful:
// eitherToFuture :: Either a b -> Future a b
const eitherToFuture = either => Future ((reject, resolve) => {
S.bimap (reject) (resolve) (either)
return () => { reject () }
})One use-case could be parsing JSON:
const log = msg => x => (console.log (msg, x), x)
const logError = msg => x => (console.error (msg, x), x)
const parseJson = S.encase (JSON.parse)
// futureParseJson :: Error a, Object b => String -> Future a b
const futureParseJson = S.pipe ([
parseJson,
log ('after parseJson'), // <- debugging
eitherToFuture,
])
const getJson = fork
(logError ('Rejection:'))
(log ('Resolved:'))
// main
const validJsonString = '[{"foo":"bar"},{"foo":null}]'
const invalidJsonString = '[{"foo":"bar"}{"foo":null}]'
getJson (futureParseJson (validJsonString))
// -> after parseJson Right ([{"foo": "bar"}, {"foo": null}])
// Resolved: [ { foo: 'bar' }, { foo: null } ]
getJson (futureParseJson (invalidJsonString))
// -> after parseJson Left (new SyntaxError ("Unexpected token { in JSON at position 14"))
// Rejection: SyntaxError: Unexpected token { in JSON at position 14
// at parse (<anonymous>)What do you think?
Metadata
Metadata
Assignees
Labels
No labels