Either/IO Exercise 5 & 6
Last example
// Exercise 5
// ==========
// Use getHref() / getProtocal() and runIO() to get the protocal of the page.
var getHref = function(){ return location.href; }.toIO();
var getProtocal = compose(_.head, _.split('/'));
var ex5 = compose(map(getProtocal), getHref);
console.log("--------Start exercise 5--------");
assertEqual('http:', runIO(ex5(null)));
console.log("exercise 5...ok!");
Left
implementation will explicitily not run the rest of your app, but the error message will bubble up.
// Exercise 6*
// ==========
// Write a function that returns the Maybe(email) of the User from getCache(). Don't forget to JSON.parse once it's pulled from the cache so you can _.get() the email
// setup...
localStorage.user = JSON.stringify({email: "george@foreman.net"});
var getCache = function(x){ return Maybe(localStorage[x]); }.toIO();
// var ex6 = undefined
var ex6 = compose(map(map(compose(_.get('email'), JSON.parse))), getCache);
assertDeepEqual(Maybe("george@foreman.net"), runIO(ex6('user')));
console.log("exercise 6...ok!");
You cannot just do var ex6 = compose(_.get('email'), getCache)
because the email is stringified. So you need to add:
var getStringEmail = compose(_.get('email'), JSON.parse)
But this still not enough because of the maybe
inside it. You need to map
the IO
then map
the maybe
.
var ex6 = compose(map(map(getStringEmail)), getCache)
This is why there's two map
s above. (var Type = compose(IO, Maybe)
)
So we composed behaviours above. We composed error handling, type checking, IO. Doesn't seem easy to compose a null
check with behaviour but this is what we did here very easily.
Later we will use monads and lens to simplify using map
s everywhere.