[JS Compose] 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(3).map(x => x + 1).map(x => x / 2);
console.log(res1.toString()); // Right(2)

const res2 = Left(3).map(x => x + 1).map(x => x / 2);
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(1))
  .fold(e => "no color found", s => s.toUpperCase());

console.log(res) //0000FF
const res = findColor("yellow")
  .map(s => s.slice(1))
  .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(1).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.

时间: 2024-09-30 19:20:44

[JS Compose] Enforce a null check with composable code branching using Either的相关文章

160304-02、JS 中如何判断null 和undefined

JavaScript 中有两个特殊数据类型:undefined 和 null,下节介绍了 null 的判断,下面谈谈 undefined 的判断. 以下是不正确的用法: var exp = undefined;if (exp == undefined){    alert("undefined");} exp 为 null 时,也会得到与 undefined 相同的结果,虽然 null 和 undefined 不一样.注意:要同时判断 undefined 和 null 时可使用本法.

js报TypeError $(...) is null错误,jquery失效的原因及解决办法

最近在工作中发现个问题,原本好好的网页,写了一些自己的jquery代 码之后,竟然总是不起作用,无论写的多么简单,都不起作用,似乎jquery失效了一般,在火狐下调试看了下,页面报TypeError $(...) is null这种错误,找了半天原因最后发现竟是页面中加载的一个插件给捣的鬼,是它将jquery的$方法给覆盖了.对于这个问题,现在分享两种解决方法. (1)删冲突插件,jquery作为基础库,当然是没有理由被删了.这个方法最直接了. (2)将jquery的$方法改名,具体改名方法如下

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 module/project settings. 会报这个错误是因为你工程没有make.因为Findbugs并不是针对你的源代码进行检测,而是根据编译后文件(如:class.dex)进行检测. 所以如果你的工程是刚从git或者svn clone下来的,还没有make,就会出现这个问题. FindBugs

[JS Compose] Understand 'Box' or 'Container', they are just like Array!

We'll examine how to unnest function calls, capture assignment, and create a linear data flow with a type we call Box. This is our introduction to working with the various container-style types. At first, might not be comforable with 'Box' or 'Contai

JS中NaN、null、Undefined区别

1.NaN(not a number)非数字.不和任何数字相等,包括自己本身,可以用isNaN()判断,当praseInt()和praseFloat()不能解析时返回NaN.NaN为number对象下的一个属性,number.NaN typeof(NaN)   //return number NaN == NaN   //return FALSE 2.null 表示尚未存在的对象, 3.undefined表示尚未初始化   var a:alert(a)  //return undefined 在

[JS Compose] 3. Use chain for composable error handling with nested Eithers (flatMap)

We refactor a function that uses try/catch to a single composed expression using Either. We then introduce the chain function to deal with nested Eithers resulting from two try/catch calls. For example we have this code using try & catch: const getPo

JS中如何判断null、undefined与NaN

1.判断undefined: Js代码   <span style="font-size: small;">var tmp = undefined; if (typeof(tmp) == "undefined"){ alert("undefined"); }</span> 说明:typeof 返回的是字符串,有六种可能:"number"."string"."boolean&

js中使用0 “” null undefined需要注意

注意:在js中0为空(false) ,代表空的还有"",null ,undefined: 如果做判断if(!上面的四种值):返回均为false console.log(!null);// trueconsole.log(!0);//trueconsole.log(!"");// trueconsole.log(!undefined);// true console.log(0=="");//true console.log(0==" &

JS中undefined、null以及NaN之间的区别,以及对象属性赋值的面试题

(1)以下三种情况typeof 返回类型为undefined --当变量未初始化时 --变量未定义时 --函数无明确返回值时(函数没有返回值时返回的都是undefined) (2)Null 类型 undefined 是由null派生处理的,因此undefined == null undefined 是声明了但是没有初始化的该变量, null表示尚未存在的对象 . (3)NaN 值 是一个特殊值,表示非数(Not a Number),类型转换失败就会返回NaN --NaN 不等于自己,即 NaN