函数式编程-Maybe函子篇

在这里插入图片描述

简介
我们在编程的过程中可能会遇到很多错误,需要对这些错误做相应的处理
maybe函子的作用就是可以对外部的空值情况做处理(控制副作用在允许的范围)如下
举例
//maybe函子 处理异常函子

class Maybe {
    static of(value) {
        return new Maybe(value)
    }
    constructor(value) {
        this._value = value;
    }
    map(fn) {
        return this.isNothing() ? Maybe.of(null) : Maybe.of(fn(this._value))
    }
    isNothing() {
        return this._value === null || this._value === undefined;
    }
}
let str3 = 'hello world'

let result3 = Maybe.of(str3).map(data => data.toUpperCase());

console.log(result3); //Maybe { _value: 'HELLO WORLD' }

//实验 传入 null || undefined

let result4 = Maybe.of(undefined).map(data => data.toUpperCase())

console.log(result4); //Maybe { _value: null } 没有报错

//在这里还有一个问题 多次调用map方法的话 不确定哪个函子出现问题  下个文章揭晓

谢谢观看,如有不足敬请指教

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值