[Javascript Crocks] Recover from a Nothing with the `alt` method
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的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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. ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
随机推荐
- spark作业运行过程之--DAGScheduler
DAGScheduler--stage划分和创建以及stage的提交 本篇,我会从一次spark作业的运行为切入点,将spark运行过程中涉及到的各个步骤,包括DAG图的划分,任务集的创建,资源分配, ...
- CentOS7 搭建Kafka(二)kafka篇
CentOS7 搭建Kafka(二)kafka篇 前面我们说了zookeeper的搭建,zookeeper运行后就可以着手搭建kafka了. 必看 喜欢官方文档的请移步:[http://kafka.a ...
- IO流遍历文件夹下所有文件问题
import java.io.File; /** * @author 王恒 * @datetime 2017年4月20日 下午2:24:32 * @description 递归调用 * */ publ ...
- Coursera公开课-Machine_learing:编程作业6
Support Vector Machines I have some issues to state. First, there were some bugs in original code wh ...
- 5.17 Quartz笔记
有用到构建者模式: builder---JobDetail相当于需要构建者构建出来的一个配件:JobDetail为Job实例提供了许多设置属性,以及JobDetaMap成员变量属性,它用来存储特定Jo ...
- Redis学习笔记(二)-key相关命令
Redis支持的各种数据类型包括string,list ,set ,sorted set 和hash . Redis本质上一个key-value db,所以我们首先来看看他的key.首先key也是字符 ...
- Get 和 Post
理论: Http定义了与服务器交互的不同方法,最基本的方法有4种,分别是GET,POST,PUT,DELETE.URL全称是资源描述符,我们可以这样认为:一个URL地址,它用于描述一个网络上的资源,而 ...
- Django学习案例一(blog):三. 模型生成数据
1. 什么是模型models Django中以创建类的形式来创建数据表. 在编写代码的过程中,所有对数据库的操作,都是对类和类的对象进行操作. ORM对象关系映射(Object relation ma ...
- 学习廖雪峰的Python教程之数据类型
数据类型 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视频.网页等各种各样的数据,不同的数据,需要定 ...
- VTK:VTK嵌入MFC成功
VTK作为医学显示库,得到较多使用.作为较为上层的设计,对OpenGL进行了封装,并且有Windows.Linux.安卓等开发版本,可移植性较强. 不过VES暂时没有编译成功. 以下是嵌入MFC-ID ...