[JS Compose] 2. Enforce a null check with composable code branching using Either
We define the Either type and see how it works. Then try it out to enforce a null check and branch our code.
Now, we try to make Box more useful. We want to do a force null check by define "Right" and "Left" tow boxes.
What "Right" does is, apply the logic passed in to the value Box has.
What "Left" does is, ingore the logic and just return the value.
const Right = x => ({
map: f => Right(f(x)),
toString: () => `Right(${x})`
}); const Left = x => ({
map: f => Left(x),
toString: () => `Left(${x})`
});
Example:
const res1 = Right().map(x => x + ).map(x => x / );
console.log(res1.toString()); // Right(2) const res2 = Left().map(x => x + ).map(x => x / );
console.log(res2.toString()); // Left(3)
The logic here we try to complete, is the function either call "Right" or "Left". To see a more useful case, we need to define our 'fold' function.
const Right = x => ({
map: f => Right(f(x)),
fold: (f, g) => g(x), // If Right, run function g
toString: () => `Right(${x})`
}); const Left = x => ({
map: f => Left(x),
fold: (f, g) => f(x), // If Left, run function f
toString: () => `Left(${x})`
});
Because in real case, we never know it is Right or Left get called, so in fold function, we defined two params, if it is Right get called, we will call second param g, if it is Left get called, we will call first param f.
How how about we build a function to find color, if the color is defined, we return its value, if not, we return "No color"!
const findNullable = x =>
x != null ? Right(x) : Left(null); const findColor = name =>
findNullable({red: "#ff0000", green: "#00ff00", blue: "#0000ff"}[name]); const res = findColor("blue")
.map(s => s.slice())
.fold(e => "no color found", s => s.toUpperCase()); console.log(res) //0000FF
const res = findColor("yellow")
.map(s => s.slice())
.fold(e => "no color found", s => s.toUpperCase()); console.log(res); // no color found
Now, if the color is found, then it log out the color value, if not found, then show the error message.
So let's think about it, what if we doesn't wrap findColor function into Box? For example, it looks like this:
const findColor = name =>
{red: "#ff0000", green: "#00ff00", blue: "#0000ff"}[name];
Then we do:
const findColor = name =>
{red: "#ff0000", green: "#00ff00", blue: "#0000ff"}[name]; const res = findColor("yellow").slice().toUpperCase();
console.log(res); // Error: cannot call .slice() on Undefined!
So the benefits we get from Right and Left is it help us do null checking. If it is Left, then it will skip all the map chain. Therefore we can keep our program safe.
[JS Compose] 2. Enforce a null check with composable code branching using Either的更多相关文章
- FindBugs:Compiler output path for module can not be null. check your module/project settings问题原因
这可能是很多人在使用Android studio 该插件会发现此错误信息:Compiler output path for module can not be null. check your mod ...
- js中的undefined与null、空值的比较
最近在修改一个项目,总是报Js错误: 无法获取属性“length”的值: 对象为 null 或未定义 点开调试之后,惊奇的发现markerArr的值是undefined 所以我就将代码改成如下形式: ...
- [转]JS基础之undefined与null的区别
在JavaScript开发中,被人问到:null与undefined到底有啥区别? 一时间不好回答,特别是undefined,因为这涉及到undefined的实现原理.于是,细想之后,写下本文,请各位 ...
- js判断undefined类型,undefined,null,NaN的区别
js判断undefined类型 今天使用showModalDialog打开页面,返回值时.当打开的页面点击关闭按钮或直接点浏览器上的关闭则返回值是undefined 所以自作聪明判断 ...
- js操作css样式,null和undefined的区别?
1.js操作css的样式 div.style.width="100px"在div标签内我们添加了一个style属性,并设定了width值.这种写法会给标签带来大量的style属性, ...
- js判断undefined类型,undefined,null, 的区别详细解析
js判断undefined类型 今天使用showModalDialog打开页面,返回值时.当打开的页面点击关闭按钮或直接点浏览器上的关闭则返回值是undefined所以自作聪明判断 var reVal ...
- 【JS Note】undefined与null
在Javascript中有这两种原始类型: Undefined与Null.而这两种原始类型都各自只有一个值,分别是undefined,null. undefined: 1.变量声明后未赋值,则变量会被 ...
- js中的undefined 和null
undefined是基本数据类型 表示未定义 缺少的意思 null是引用数据类型 是对象 表示空对象 undefined是从null派生出来的 所以undefined==null true Ja ...
- JS中的Undefined和Null的区别
Undefined ①在声明变量时,如果没有给变量赋值,则这个变量就是undefined类型: ②访问未声明的变量会报错误消息,但这样的变量使用 typeof 测试,返回的值为Undefined. 即 ...
随机推荐
- Exclusive or
题目连接 题意: 每次给一个n.求 (2≤n<10500) 分析: 先说一下自己的想法,假设将n换成二进制数,也就一两千位左右,那么一位一位处理是能够接受的. 将0-n写成二进制形式后,显然全部 ...
- php7 兼容 MySQL 相关函数
php7 兼容 MySQL 相关函数 PHP7 废除了 ”mysql.dll” ,推荐使用 mysqli 或者 pdo_mysql http://PHP.net/manual/zh/mysqlinfo ...
- iTOP-4412 nfs文件系统启动
kernel command line type: 普通文件系统(本地)启动:root=/dev/mmcblk0p2 rootfstype=ext4 init=/linuxrc console=tty ...
- JS怎么判断数组类型?
1.判断对象的constructor是否指向Array,接着判断特殊的属性length,splice等.[应用的是constructor的定义:返回对象所对应的构造函数.] eg: [].constr ...
- Could not find action or result: There is no Action mapped for namespace [/] and action name [GetG
Could not find action or result: /car/GetGpsDataAction There is no Action mapped for namespace [/] ...
- Android 设置背景透明度
一些时候,我们须要为UI页面设置背景色,例如以下图所看到的: 上图已注: 背景颜色为#000000,透明度为40%: 那么.怎样在代码中表示呢? 首先须要了解: 颜色和不透明度 (alpha) 值以十 ...
- iOS_06_Mac os X
Mac os X 系统简介 * 苹果公司专门为苹果电脑设计的操作系统. * 以坚如磐石的UNIX为基础,既简单易用且功能强大. * x 是一个罗马数字正式的发音位“十”(ten),连续了先前的Mac ...
- Exsi SSH 服务配置
vi /etc/ssh/sshd_conf禁止口令验证PasswordAuthentication no禁止root登录PermitRootLogin no ESXi Shell F2--F2--Tr ...
- 【剑指offer】对面和相等的正方体
转载请注明出处:http://blog.csdn.net/ns_code/article/details/26509459 剑指offer上的全排列相关题目. 输入一个含有8个数字的数组.推断有么有可 ...
- 关于LWIP断开网线后重连问题(热插拔问题)
近期在弄STM32+LWIP协议.在网络拔掉网线情况下.无法又一次连接. 网上找了好多方法都没有实现,着实郁闷! 后来无意间看到了临时解决这一问题的方法.尽管不是那么完美,但最算能解决这个问题.分享给 ...