首页 > 代码库 > [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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。