[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 proputility 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);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值