[Javascript Crocks] Safely Access Object Properties with `prop`
In this lesson, we’ll use a Maybe to safely operate on properties of an object that could be undefined. We’ll use our initial code as the basis for a prop
utility function that can be reused with different objects and various property names. Instead of just blindly asking for a property, this version of prop
will drop us into the safe confines of a Maybe, giving us a Just
when the property exists and a Nothing
for an undefined
property. Once we’ve built up our own prop
utility, we’ll refactor the code one more time to take advantage of the built-in prop
utility provided by the crocks library.
When you want to pull out a value from object or array, you might doing like this:
const safe = require('crocks/Maybe/safe');
const { inc } = require('./utils');
const { not, compose, isNil, prop } = require('ramda'); // check the value is not undefined or null
const isNotNil = safe(compose(not, isNil));
// check object's prop value is not undefined or null
const safeProp = propName => obj => isNotNil(prop(propName, obj));
// get 'page' prop from the object as Maybe type
const safePage = safeProp('page');
// data
const qs = { page: 4, pageSize: 10, totalPages: 203 };
//default value is 1
const result = safePage(qs).option(1); console.log(result); //
Actually from the code above we write many code, we use Ramda lib for utils functions and safe prop method.
const { not, compose, isNil, prop } = require('ramda'); const isNotNil = safe(compose(not, isNil));
const safeProp = propName => obj => isNotNil(prop(propName, obj));
Actually crocks lib provide 'prop' method to simply the code:
const prop = require('crocks/Maybe/prop');
const { inc } = require('./utils'); const safePage = prop('page'); const qs = { page: , pageSize: , totalPages: };
const result = safePage(qs).option(); console.log(result);
最新文章
- .NET 实现并行的几种方式(二)
- 软件工程(FZU2015)赛季得分榜,第八回合
- clientTop、offsetTop和scrollTop的区分
- 使用javascript实现html页面直接下载网盘文件
- unity3d 关于断点下载和整个下载(用于更新)
- Flex Excel下载
- html5+php实现文件的断点续传ajax异步上传
- swagger-editor 快速REST-API 测试文档编写
- js中的数组
- 【原创翻译】Reducing Branch Delay to Zero in Pipelined Processors
- python的py文件打包成exe
- push方法的页面间跳转--
- SSAS系列——【04】多维数据(物理体系结构)
- SQL Server 2008 允许远程链接,适用于广域网和局域网
- 局域网iis添加主机头
- Alamofire源码解读系列(八)之安全策略(ServerTrustPolicy)
- Android开发之初识MVP模式
- Asp.net 程序连接orcle如果在安装 32 位 Oracle 客户端组件的情况下以 64 位模式运行,
- ajax跨域请求Flask后台
- vue 分享知识点