zoukankan      html  css  js  c++  java
  • [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!")
  • 相关阅读:
    opencv mat转IplImage*
    运行程序时命令窗口一闪而过
    python version 2.7 required,which was not found in the registry
    《深入浅出wpf》 控件
    opengl glut vs2013配置
    《深入浅出wpf》第六章 深入浅出话binding
    《深入浅出wpf》第五章 控件与布局
    十大暴利行业
    java安装与配置
    ArcGIS For Flex学习之Mapping---Select and zoom
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5855123.html
Copyright © 2011-2022 走看看