[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); // 4
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: 4, pageSize: 10, totalPages: 203 }; const result = safePage(qs).option(1); console.log(result);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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