• [Javascript] Maybe Functor


    In normal Javascript, we do undefine check or null check:

    var person = {age: 14, name: "Suvi"};
    var name = person.name ? person.name: null;

    Sometime backend data return may contain or not contain 'name' prop.

    So let's see how to define a Maybe() functor:

    var _Maybe.prototype.map = function(f) {
      return this.val ? Maybe(f(this.val)) : Maybe(null);
    }
    
    map(capitalize, Maybe("flamethrower"))
    //=> Maybe(“Flamethrower”)

    The idea of Maybe is check whetehr the Container has value or not, if not return Maybe(null), if has then return Maybe(val).

    // Exercise 3
    // ==========
    // Use safeGet and _.head to find the first initial of the user
    

    var _ = R;
    var P = PointFree;
    var map = P.fmap;
    var compose = P.compose;
    var Maybe = P.Maybe;
    var Identity = P.Id;


    var safeGet = _.curry(function(x,o){ return Maybe(o[x]) }) var user = {id: 2, name: "Albert"} console.log("--------Start exercise 3--------") var ex3 = compose(map(_.head), safeGet('name')); assertDeepEqual(Maybe('A'), ex3(user)) console.log("exercise 3...ok!")

    So after the "safeGet('name')" run, it return "Maybe('Albert')";

    Then we use map(_.head): map--> get into the Maybe to check val; 

    _.head --> Get teh 'A' or 'Albert'.

    The good thing about this is if use 'safeGet('address')' which inside 'user' object doesn't provide, then we will get 'Maybe(null)':

    "Uncaught expected Maybe(A) to equal Maybe(null) (line 68)"
    // Exercise 4
    // ==========
    // Use Maybe to rewrite ex4 without an if statement
    console.log("--------Start exercise 4--------")
    

    var _ = R;
    var P = PointFree;
    var map = P.fmap;
    var compose = P.compose;
    var Maybe = P.Maybe;
    var Identity = P.Id;

    var ex4 = function(n) {
      if(n){
        return parseInt(n);
      }
    }
    
    var ex4 = compose(map(parseInt), Maybe)
    
    
    assertDeepEqual(Maybe(4), ex4("4"))
    console.log("exercise 4...ok!")

    So when the value comes into the ex4 which we wrote, first we will get "Maybe(4)";

    Because Maybe(4) is inside a Functor, then we need to call map() on it to get value;

  • 相关阅读:
    Linux文件系统_每一个的意义
    Linux启动的流程
    Linux
    awk编程
    Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法
    spring boot get和post请求,以及requestbody为json串时候的处理
    Spring Boot快速入门
    Spring Boot 实用MyBatis做数据库操作
    极简操作无需root隐藏S8导航栏和状态栏
    springboot(三):Spring boot中Redis的使用
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5847818.html
Copyright © 2020-2023  润新知