首页 > 代码库 > [Javascript] IO Functor

[Javascript] IO Functor

IO functor doesn‘t like Maybe(), Either() functors. Instead of get a value, it takes a function.

 

API:

.toIO()  // conver a function to IOIO() // The same a to toIO; but this is a just static methodrunIO //IO is lazy, just like Observable, if you don‘t run it, it has no side effect

 

Examples:

/*Cover to IO*/var email_io = IO(function(){ return $("#email").val() }var getValue = http://www.mamicode.com/function(sel){ return $(sel).val() }.toIO()/*Example runIO*/var email_io = IO(function(){ return $("#email").val() })var msg_io = map(concat("welcome "), email_io)runIO(msg_io)//=> ”welcome steve@foodie.net”

 

// Exercise 4// ==========// Get the text from the input and strip the spacesconsole.log("--------Start exercise 4--------")var getValue = http://www.mamicode.com/function(x){ return document.querySelector(x).value }.toIO()var stripSpaces = function(s){ return s.replace(/\s+/g, ‘‘); }var ex4 = compose(map(stripSpaces), getValue)assertEqual("honkeytonk", runIO(ex4(#text)))console.log("exercise 4...ok!")// Exercise 5// ==========// Use getHref() / getProtocal() and runIO() to get the protocal of the page.var getHref = http://www.mamicode.com/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("http://www.google.fi")))console.log("exercise 5...ok!")// 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 log = function(x){  console.log(x.toString());  return x;}var getCache = function(x){ return Maybe(localStorage[x]); }.toIO();var getEmail = compose(_.get(email), JSON.parse);var ex6 = compose(map(map(getEmail)), getCache); // one map for Maybe, one map for IOassertDeepEqual(Maybe("george@foreman.net"), runIO(ex6(user)))console.log("exercise 6...ok!")

 

[Javascript] IO Functor