[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(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.

posted @   Zhentiw  阅读(255)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2014-12-13 [AngularJS] Using Services in Angular Directives
点击右上角即可分享
微信分享提示