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的更多相关文章

  1. 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 ...

  2. js中的undefined与null、空值的比较

    最近在修改一个项目,总是报Js错误: 无法获取属性“length”的值: 对象为 null 或未定义 点开调试之后,惊奇的发现markerArr的值是undefined 所以我就将代码改成如下形式: ...

  3. [转]JS基础之undefined与null的区别

    在JavaScript开发中,被人问到:null与undefined到底有啥区别? 一时间不好回答,特别是undefined,因为这涉及到undefined的实现原理.于是,细想之后,写下本文,请各位 ...

  4. js判断undefined类型,undefined,null,NaN的区别

    js判断undefined类型 今天使用showModalDialog打开页面,返回值时.当打开的页面点击关闭按钮或直接点浏览器上的关闭则返回值是undefined   所以自作聪明判断       ...

  5. js操作css样式,null和undefined的区别?

    1.js操作css的样式 div.style.width="100px"在div标签内我们添加了一个style属性,并设定了width值.这种写法会给标签带来大量的style属性, ...

  6. js判断undefined类型,undefined,null, 的区别详细解析

    js判断undefined类型 今天使用showModalDialog打开页面,返回值时.当打开的页面点击关闭按钮或直接点浏览器上的关闭则返回值是undefined所以自作聪明判断 var reVal ...

  7. 【JS Note】undefined与null

    在Javascript中有这两种原始类型: Undefined与Null.而这两种原始类型都各自只有一个值,分别是undefined,null. undefined: 1.变量声明后未赋值,则变量会被 ...

  8. js中的undefined 和null

    undefined是基本数据类型 表示未定义 缺少的意思 null是引用数据类型  是对象 表示空对象 undefined是从null派生出来的  所以undefined==null  true Ja ...

  9. JS中的Undefined和Null的区别

    Undefined ①在声明变量时,如果没有给变量赋值,则这个变量就是undefined类型: ②访问未声明的变量会报错误消息,但这样的变量使用 typeof 测试,返回的值为Undefined. 即 ...

随机推荐

  1. 数据结构(C实现)------- 单链表

    在单链表中,每个结点包括两部分:存放每个数据元素本身信息的数据域和存放其直接后继存储位置的指针域. 单链表结点的类型描写叙述: typedef int ElemType; typedef struct ...

  2. 车牌识别--S5PV210測试第二次优化

    优化: 1.RGB转HSV 浮点运算改成定点运算: 2.匹配模板由图片改成C语言数组: 3.优化測试BMP车牌图片读取(两层for循环改为一层for循环). 总体相比优化之前时间降低110ms左右. ...

  3. Fragment-按返回键程序退出

    今天在做fragment的时候,发现一个问题,当我的界面停留在fragment的时候,按物理返回键,这时候会推出整个应用.这当然不是我们期望的,我们期望按返回键以后,应用界面返回添加fragment之 ...

  4. shell-手机屏幕录制

    今天在做android联系的时候,想要把自己写的demo效果记录下来.在网上发现了录制手机屏幕的方法,如下 adb shell screenrecord /sdcard/demo.mp4 解释 adb ...

  5. @JSONField 注解说明

    转自:https://blog.csdn.net/suyimin2010/article/details/80617538 导入@JSONField 注解: import com.alibaba.fa ...

  6. spring定时器完整

    介绍:在开发中,我们经常需要一些周期性就进行某一项操作.这时候我们就要去设置个定时器,Java中最方便.最高效的实现方式是用java.util.Timer工具类,再通过调度java.util.Time ...

  7. JVM 基础知识(GC)

    几年前写过一篇关于JVM调优的文章,前段时间拿出来看了看,又添加了一些东西.突然发现,基础真的很重要.学习的过程是一个由表及里,再由里及表的过程,所谓的"温故而知新".而真正能走完 ...

  8. Codefroces Round#427 div2

    A. Key races time limit per test 1 second memory limit per test 256 megabytes input standard input o ...

  9. 如果把父组件的数据实时的传递到子组件:用watch

    1.在子组件使用watch来监听传递给子组件的数据,然后更新子组件的数据. 2.watch和computed结合使用效果非常好. 参考链接:https://blog.csdn.net/zhouweix ...

  10. 前端项目中常用es6知识总结 -- let、const及数据类型延伸

    项目开发中一些常用的es6知识,主要是为以后分享小程序开发.node+koa项目开发以及vueSSR(vue服务端渲染)做个前置铺垫. 项目开发常用es6介绍 1.块级作用域 let const  2 ...