zoukankan      html  css  js  c++  java
  • [Javascript Crocks] Compose Functions for Reusability with the Maybe Type

    We can dot-chain our way to great success with an instance of Maybe, but there are probably cases where you need to apply the same series of transformations against different Maybes. In this lesson, we’ll look at some point-free versions of some common Maybe methods and see how we can compose them together to get a reusable function that can be applied to any Maybe instance.

    We are going to rewrite the following code by using function composion:

    const crocks = require('crocks');
    const {and, isString, Maybe, prop, safe, option, map, alt, chain} = crocks;
    const {not, isEmpty, compose, converge, join, split, toLower} = require('ramda');
    
    ///////////////UTILS/////////////////
    const joinKey = compose(join('_'),  split(' '), toLower);
    const isNotEmpty = compose(
        not,
        isEmpty
    )
    const isNonEmptyString = and(isNotEmpty, isString);
    /*const isNonEmptyString = R.converge(
        R.and,
        [
            isNotEmpty,
            isString
        ]
    );*/
    
    const createUrl = key =>`https://egghead.io/articles/${joinKey(key)}`;
    
    ////////////////MAIN////////////////
    
    const article = {
         id: 1,
         name: 'Learn FP with this one weird trick'
    };
    
    /*
    const getUrl = obj =>
        prop('name', obj) // Maybe(string)
            .chain(safe(isNonEmptyString)) // Maybe(string) --safe(isNonEmptyString)--> Maybe(Maybe(String)) --chain--> Maybe(String)
            .alt(Maybe.of('Nope')) // Nothing -> Just('Nope')
            .map(createUrl)
            .option('default');
      */
     
    const getSafeName = compose(
        chain(safe(isNonEmptyString)),
        prop('name')
    );
    const getUrlOrDefault = compose(
        option('Not valid URL'),
        map(createUrl)
    );
    const getUrl = compose(
        getUrlOrDefault,
        getSafeName
    );
    const getUrlOrNope = compose(
        getUrlOrDefault,
        alt(Maybe.of('Nope')),
        getSafeName
    ) 
    const res = getUrl(article);
    console.log(res);   
  • 相关阅读:
    jQuery实现图片延迟加载
    小猪学设计模式之—装饰者模式
    设计原则—依赖倒转原则
    ASP.NET MVC 在子页中引用头文件
    关于博客
    关于借钱
    面向对象编程(OOP)基础之UML基础
    C#抽象类、抽象方法、抽象属性
    小猪学设计模式——门面模式(外观模式)
    Eclipse 快捷键
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9037945.html
Copyright © 2011-2022 走看看