[Javascript Crocks] Make your own functions safer by lifting them into a Maybe context

本文介绍如何利用safeLift函数简化Maybe上下文中的函数调用,避免直接修改原始函数或输入值,通过示例展示了safeLift的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You probably have functions that aren’t equipped to accept a Maybe as an argument. And in most cases, altering functions to accept a specific container type isn’t desirable. You could use map, passing in your function, or you could “lift” your function into a Maybe context. In this lesson, we’ll look at how we can get a function that accepts raw values to work with our Maybe container without the need to modify the original function or the input values.

 

Imaging you want to double a number:

const crocks = require('crocks');
const { safeLift, safe, isNumber } = crocks;

const dbl = n => n * 2;

const safeDbl = n => safe(isNumber, n).map(dbl);

const res = safeDbl(2).option(0);

console.log(res)

Calling 'safe(pred, n).map(fn)' is also a common partten.

 

We can use 'safeLift' to simplfiy the code:

const crocks = require('crocks');
const { safeLift, safe, isNumber } = crocks;

const dbl = n => n * 2;
/*
const safeDbl = n => safe(isNumber, n).map(dbl);
*/

const safeDbl = safeLift(isNumber, dbl);
const res = safeDbl(2).option(0);

console.log(res)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值