[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 ...
随机推荐
- Coursera Algorithms week3 归并排序 练习测验: Shuffling a linked list
题目原文: Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items un ...
- element快速开发建站的动态UI------优
网站快速成型工具 只为这样的你: Element,一套为开发者.设计师和产品经理准备的基于 Vue 2.0 的组件库,提供了配套设计资源,帮助你的网站快速成型 http://element.elem ...
- MYSQL 数据库命令行终端操作笔记
1.数据库登录: 1.登录本地的MYSQL数据库:mysql -u root -p 2.连接远程主机上的MYSQL数据库:mysql -h 192.168.191.2 -u root -p 123 ...
- java 关键字与保留字
Java 关键字列表 (依字母排序 共51组),所有的关键字都是小写,在MyEclipse中都会显示不同的颜色: abstract, assert,boolean, break, byte, case ...
- E - Perfect Number
Problem description We consider a positive integer perfect, if and only if the sum of its digits is ...
- MemcachedClient 使用说明
上一篇介绍了Memcached基本使用方法<Memcached使用手册>,下面介绍java如何操作memcached.使用的是java_memcached-release_2.6.6. 一 ...
- 171129-workaround on ubuntu-seting up piston for steem
setup ubuntu environment variables sudo vi /etc/environment Then set all below variables: percentCha ...
- SQL Server 一个简单的游标
先看一下原表: DECLARE @id INT; DECLARE @name NVARCHAR(100); DECLARE c_department CURSOR FOR SELECT StuID, ...
- 使用cookies查询商品详情
易买网项目完工,把一些新知识记录下来,以便以后查阅,也方便他人借阅.介绍使用cookies查询商品详情. 第一步:建立商品实体类. 第二步:连接Oracle数据库. 第三步:使用三层架构. 效果图如下 ...
- centos开机运行级别更改
1.使用命令切换运行级别/目标 # systemctl isolate multi-user.target //切换到运行级别3,该命令对下次启动无影响,等价于telinit 3 # systemct ...