[Javascript Crocks] Flatten Nested Maybes with `chain`

Sometimes, we run into situations where we end up with a Maybe within the context of another Maybe. Nested structures like this can get really confusing to work with. In this lesson, we’ll look at an example of this and see how chaincan help us out by flattening the nested Maybe

 

As we all know, inside an array return another array is nested array.

Inside observable return another observable get Observable of Observable.

 

The same inside Just return another Just, we get Just of Just:

复制代码
const prop = require('crocks/Maybe/prop');
const propPath = require('crocks/Maybe/propPath');

/**
 * return Maybe type
 */
const getUser = id =>
    new Promise((resolve, reject) => {
        const result = {
            status: 200,
            body: {
                id: 1,
                username: 'tester',
                email: 'test@gmail.com',
                address: {
                    street: '111 E. West St',
                    city: 'Anywhere',
                    state: 'PA',
                    postalCode: '19123-4567'
                }
            }
        }
        resolve(prop('body', result)); // return Just {}
    });


const getPostalCode = propPath(['address', 'postalCode']); 

getUser(1)
    .then(user => user.map(getPostalCode)) // map to Just {} --> Just Just '19123-4567'
    .then(console.log); // Just Just "19123-4567"
复制代码

Inside getUser function we return a Just type object. Then from propPath, we get Just Just type object. That's why we need flatten it.

 

The way to solve the problem is using flat map which is called 'chain' in Crocks.

getUser(1)
    .then(user => user.chain(getPostalCode).option("not available")) 
    .then(console.log); // "19123-4567"

 

posted @   Zhentiw  阅读(516)  评论(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
点击右上角即可分享
微信分享提示