[Javascript Crocks] Flatten Nested Maybes with `chain`
2024-08-30 22:20:11
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 chain
can 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: ,
body: {
id: ,
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()
.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()
.then(user => user.chain(getPostalCode).option("not available"))
.then(console.log); // "19123-4567"
最新文章
- 基于vw的响应式排版布局
- jdbc基本查询方法
- zepto.js之ajax剖析
- BZOJ3226[Sdoi2008]校门外的区间 题解
- tomcat 调优
- insert时出现主键冲突的处理方法【转载】
- HTML入门知识汇总
- 【Thymeleaf】Thymeleaf模板对html实时刷新
- python中深拷贝与浅拷贝
- Sublime Text3—常用插件Emmet
- session和cookies
- Golang 实现 set 集合,变相实现 切片去重、排序 功能
- python 类似java的三目运算符
- 阿里云服务器上安装mysql的详细步骤
- hdoj1005(循环,找规律)
- 【工具推荐】截图工具 Snipaste
- 2018.06.29 NOIP模拟 排列(线段树)
- ZigBee 学习资源
- streamsets stream selector 使用
- nginx实现openfire负载均衡