[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 ...
随机推荐
- operator[] 重载
#include <iostream>#include <vector>#include <string> class Assoc { struct Pair ...
- Genuitec
- php 原生简版日志导出
<?phpfunction writeLog($msg){ $logFile = date('Y-m-d').'.txt'; $msg = date('Y-m-d H:i:s').' >& ...
- MSSQL:查看作业情况
select j.name 'Job名', j.description '描述', j.ENABLED job_enabled, cast(js.last_r ...
- Mysql数据库系列
详情点击 MySQL基础 Mysql表操作 Mysql插入 更新 删除 查询操作 Mysql创建用户和授权 基本的Mysql语句 Mysql库的操作 Mysql表的操作 Mysql数据类型(一) My ...
- strcpy自实现
为了避免strcpy源串覆盖问题(P220),自实现strcpy. #include <stdio.h> #include <string.h> #include <as ...
- facade 模式和gateway模式的区别
原文:http://stackoverflow.com/questions/4422211/what-is-the-difference-between-facade-and-gateway-desi ...
- nginx编译安装新模块
nginx的模块是需要重新编译nginx,而不是像apache一样配置文件引用.so 这里以安装第三方ngx_http_google_filter_module模块为例 下载第三方扩展模块ngx_ht ...
- ie8及其以下版本兼容性问题之input file隐藏上传文件
文件上传时,默认的file标签很难看,而且每个浏览器下都有很大差距.因此我们基本都把真正的file标签给隐藏,然后创建一个标签来替代它.但是由于IE出于安全方面的考虑上传文件时必须点击file的浏览按 ...
- SQLite 在 Android 的应用
Android提供了创建和使用SQLite数据库的API(Application Programming Interface,应用程序编程接口). 在Android系统中,主要由类SQLiteData ...