Once we’re using Maybes throughout our code, it stands to reason that at some point we’ll get a Maybe and want to continue applying transformations. We might get a Nothing and want to perform those same transformations on some default value. In this lesson, we’ll do exactly that! We’ll see how we can use the alt method on the Maybe to recover from a Nothing and continue applying transformations with a Just.

The use case is that you get a Nothing from previous transformation, but you wish not to stop with Nothing, you want oto provide a default Maybe value and continue the process.

const crocks = require('crocks')
const { and, compose, isEmpty, isString, Maybe, not, prop, safe } = crocks
const { join, split, toLower } = require('ramda') const article = {
id: ,
name: 'Learning crocksjs functional programming library'
}; const createUrlSlug = compose(join('-'), split(' '), toLower);
const createUrl = slug => `https://egghead.io/articles/${slug}`;
const createUrlFromName = compose(createUrl, createUrlSlug);
const isNonEmptyString = and(not(isEmpty), isString); const getArticleName = obj => prop('name', obj)
.chain(safe(isNonEmptyString)) // If previous return Just(""), we want to continue check make sure it is not empty, other return Nothing
.alt(Maybe.of('page not found')); // If return Nothing then use alt value const getArticleUrl = obj => getArticleName(obj)
.map(createUrlFromName)
.option('default'); const url = getArticleUrl(article); console.log(url)

We are also able to chain multi 'alt' together, it will return first Just():

const bad = Nothing()
const good = Just()
const anotherGood = Just()
console.log(Nothing()
.alt(bad)) // Nothing console.log(Nothing()
.alt(bad)
.alt(good)) // Just 42 console.log(Nothing()
.alt(bad)
.alt(good)
.alt(anotherGood)) // Just 42

More example:

const Maybe = require('crocks/Maybe')
const alt = require('crocks/pointfree/alt')
const converge = require('crocks/combinators/converge')
const prop = require('crocks/Maybe/prop') const {Just} = Maybe; // maybeGetDisplay :: a -> Maybe b
const maybeGetDisplay = prop('display') // maybeGetFirst :: a -> Maybe b
const maybeGetFirst = prop('first') // maybeGetLast :: a -> Maybe b
const maybeGetLast = prop('last') // maybeConcatStrings :: Maybe String -> Maybe String -> Maybe String
const maybeConcatStrings = x => y => Just(x => y => x + ' ' + y).ap(x).ap(y).alt(x).alt(y) // maybeMakeDisplay :: a -> Maybe String
const maybeMakeDisplay = converge(maybeConcatStrings, maybeGetFirst, maybeGetLast) // maybeGetName :: a -> Maybe b
const maybeGetName = converge(alt, maybeGetDisplay, maybeMakeDisplay) console.log(maybeMakeDisplay({ display: 'Jack Sparrow' }))
//=> Just('Jack Sparrow') console.log(maybeMakeDisplay({ first: 'J', last: 'S' }))
//=> Just('J S') console.log(maybeMakeDisplay({ display: 'Jack Sparrow', first: 'J', last: 'S' }))
//=> Just('Jack Sparrow') console.log(maybeMakeDisplay({ first: 'J' }))
//=> Just('J') console.log(maybeGetName({ last: 'S' }))
//=> Just('S')

[Javascript Crocks] Recover from a Nothing with the `alt` method的更多相关文章

  1. [Javascript Crocks] Recover from a Nothing with the `coalesce` Method

    The alt method allows us to recover from a nothing with a default Maybe, but sometimes our recovery ...

  2. [Javascript Crocks] Apply a function in a Maybe context to Maybe inputs (curry & ap & liftA2)

    Functions are first class in JavaScript. This means we can treat a function like any other data. Thi ...

  3. [Javascript Crocks] Make your own functions safer by lifting them into a Maybe context

    You probably have functions that aren’t equipped to accept a Maybe as an argument. And in most cases ...

  4. [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 wh ...

  5. [Javascript Crocks] Flatten Nested Maybes with `chain`

    Sometimes, we run into situations where we end up with a Maybe within the context of another Maybe. ...

  6. [Javascript Crocks] Safely Access Nested Object Properties with `propPath`

    In this lesson, we’ll look at the propPath utility function. We’ll ask for a property multiple level ...

  7. [Javascript Crocks] Safely Access Object Properties with `prop`

    In this lesson, we’ll use a Maybe to safely operate on properties of an object that could be undefin ...

  8. [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 ...

  9. [Javascript Crocks] Understand the Maybe Data Type

    In this lesson, we’ll get started with the Maybe type. We’ll look at the underlying Just and Nothing ...

随机推荐

  1. golang单点推送

    package main import ( "encoding/json" "flag" "fmt" "log" &qu ...

  2. web 应用

    一.web应用 web应用程序是一种可以通过web访问的应用程序,程序 的最大好处是用户很容易访问应用程序,用户只需要有浏览器 即可,不需要安装其他团建,用用程序有两种模式C/S.B/S.C/S是客户 ...

  3. 使用 SqlBulkCopy 批量插入数据

    /// <summary> /// 使用SqlBulkCopy将DataTable中的数据批量插入数据库中 /// </summary> /// <param name= ...

  4. 【HTTP】如何正常关闭连接

    参考:<HTTP权威指南> 所有HTTP客户端.服务器或者代理都可以任意时刻关闭一条TCP传输连接.但是服务器永远无法确定它关闭“空闲”连接的那一刻,在线路那一头的客户端有没有数据要发送. ...

  5. Vue掉坑记

    本文章汇总学习过程中掉入和不理解的坑,会持续更新,请保持关注 1.过滤器类 搜索过滤 2.修饰符 修饰符汇总 3.webpack webpack+vuecli打包路径 4.Vue后台管理框架 组件后台 ...

  6. 使用T-sql建库建表建约束

    为什么要使用sql语句建库建表? 现在假设这样一个场景,公司的项目经过测试没问题后需要在客户的实际环境中进行演示,那就需要对数据进行移植,现在问题来了:客户的数据库版本和公司开发阶段使用的数据库不兼容 ...

  7. vim之快速跳转

    光棍节啦, 淘东西的闲暇上来发vim旅途第一篇日志. 为什么呢? 因为今天是我媳妇的生日, 我用这种只有我知道的方式来纪念一下. ^_^, 宝宝生日快乐! 开篇先说明日志布局, vim学习记录连载中所 ...

  8. C# 彻底关闭程序,包括循环

    System.Environment.Exit(System.Environment.ExitCode); this.Dispose(); this.Close();

  9. cannot find Toolkit in /usr/local/cuda-8.0

    对于新版本ubuntukylin17.04安装CUDA时出现 cannot find Toolkit in /usr/local/cuda-8.0 问题 尝试了各种方法,均不妥当...... 参考:h ...

  10. Ubuntu安装中文语言包

    使用Ubuntu 默认的界面感觉不习惯,于是安装KDE界面. 1.安装kde 使用命令行: sudo apt-get install kubuntu-desktop 安装后发现不能使用中文, 在 se ...