[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 types and create a simple utility function to create a Maybe from a value. Then we’ll see how we can apply functions to values and skip invocation for values that might cause errors or unexpected results.

 

Most of time, we will meet this kind of problem in our code:

const {inc} = require('./utils');

const res = inc(2); // 3
const res1 = inc('2'); // 21
const res2 = inc(undefined); // NaN

We expect the function 'inc' can help to increase the value by 1, but if we pass the string type of undefined, we won't get the result we want.

 

Of course, you can update your inc function like that:

复制代码
// from
const inc = n => n + 1;

// to
const inc = n => typeof n === 'number' ? n + 1: 0;

module.exports = {
    inc
};
复制代码

But it only works if you have full control of your code, if you are using a thrid-party lib, then it doesn't work.

 

Install:

npm i -S crocks

 

By import Maybe from crocks lib:

const Maybe = require('crocks/Maybe');

You two APIs to use:

Maybe.Just(2) // Just 2 
Maybe.Nothing() // Nothing

 

Update our code:

复制代码
// utils.js
const inc = n => n + 1;

module.exports = {
    inc
};


// index.js
const {inc} = require('./utils');
const Maybe = require('crocks/Maybe');

const safeNum = n => typeof n === 'number' ? Maybe.Just(n) : Maybe.Nothing();
const input = safeNum(2); // Just 3
// const input = safeNum('2'); // Nothing
// const input = safeNum(undefined); // Nothing
const result = input
    .map(inc);

console.log(result); // Just 3
复制代码

Now we get 'Just 3' as a result, but we want the actual value and also apply a default value 0:

复制代码
const safeNum = n => typeof n === 'number' ? Maybe.Just(n) : Maybe.Nothing();
const input = safeNum(2); // 3
// const input = safeNum('2'); // 0
// const input = safeNum(undefined); // 0

const result = input
    .map(inc)
    .option(0) // unwrap the value and give a default value;

console.log(result); 
复制代码

 

posted @   Zhentiw  阅读(201)  评论(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工具
历史上的今天:
2017-05-11 [Angular] Using useExisting provider
2017-05-11 [Angular] Providers and useFactory
2017-05-11 [Angular] Using InjectionToken
点击右上角即可分享
微信分享提示