[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 IO
IO() // The same a to toIO; but this is a just static method
runIO //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 = 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 spaces
console.log("--------Start exercise 4--------")

var getValue = 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 = 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 IO

assertDeepEqual(Maybe("george@foreman.net"), runIO(ex6('user')))
console.log("exercise 6...ok!")
原文地址:https://www.cnblogs.com/Answer1215/p/5855123.html