简介
我们在编程的过程中可能会遇到很多错误,需要对这些错误做相应的处理
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方法的话 不确定哪个函子出现问题 下个文章揭晓
谢谢观看,如有不足敬请指教