zoukankan      html  css  js  c++  java
  • [Javascript Crocks] Create a Maybe with a `safe` Utility Function

    In this lesson, we’ll create a safe function that gives us a flexible way to create Maybes based on a value and a predicate function that we supply. We’ll verify its behavior with values that satisfy the predicate, and values that do not.

    We can write more functional approach, for example write predicate functions:

    const isNumber = n => typeof n === 'number' ? Maybe.Just(n) : Maybe.Nothing();
    const isString = s => typeof s === 'string' ? Maybe.Just(s) : Maybe.Nothing();

    High order function:

    const safe = pred => val => pred(val);
    
    const safeNum = safe(isNumber);
    const safeStr = safe(isString);

    Those functions are useful when we want use in large scale application, because those are composable.

    Full code demo:

    const {inc, upper} = require('./utils');
    const Maybe = require('crocks/Maybe');
    
    const isNumber = n => typeof n === 'number' ? Maybe.Just(n) : Maybe.Nothing();
    const isString = s => typeof s === 'string' ? Maybe.Just(s) : Maybe.Nothing();
    const safe = pred => val => pred(val);
    
    const safeNum = safe(isNumber);
    const safeStr = safe(isString);
    
    const inputN = safeNum(2); // Just 3 -> 3
    const inputS = safeStr('test'); //  Just TEST -> TEST
    const input = safeStr(undefined); // Nothing -> 0
    
    const result = inputS
        .map(upper)
        .option("");
    
    console.log(result);


    Crocks lib also provides those functions, you actually don't need to write it by yourself.

    https://evilsoft.github.io/crocks/docs/functions/predicate-functions.html

    const {inc, upper} = require('./utils');
    const Maybe = require('crocks/Maybe');
    const safe = require('crocks/Maybe/safe');
    const { isNumber, isString} = require('crocks/predicates');
    
    /*
    const isNumber = n => typeof n === 'number' ? Maybe.Just(n) : Maybe.Nothing();
    const isString = s => typeof s === 'string' ? Maybe.Just(s) : Maybe.Nothing();
    const safe = pred => val => pred(val);
    */
    const safeNum = safe(isNumber);
    const safeStr = safe(isString);
    
    const inputN = safeNum(2); // Just 3 -> 3
    const inputS = safeStr('test'); //  Just TEST -> TEST
    const input = safeStr(undefined); // Nothing -> 0
    
    const result = inputS
        .map(upper)
        .option("");
    
    console.log(result);
  • 相关阅读:
    springMVC源码学习地址
    JVM架构和GC垃圾回收机制详解
    String StringBuffer和StringBuilder区别及性能
    java reflect反射获取方法变量参数
    springMVC数据模型model,modelmap,map,@ModelAttribute的相互关系
    java abstract构造函数调用
    springMVC源码学习之addFlashAttribute源码分析
    LeetCode 404. Sum of Left Leaves
    利用JavaFX访问MySQL数据库
    LeetCode 111. Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9026265.html
Copyright © 2011-2022 走看看