我们在编程过程中可能会遇到很多错误,需要对这些错误做相应的处理
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 r = MayBe.of('hello world').map(x => x.toUpperCase())
let r = MayBe.of('hello world').map(x => x.toUpperCase()).map(x => null).map(x => x.split(' '))
console.log(r)
MayBe函子的问题在于不知道是哪次调用出现了问题。Either函子解决这个问题=》下篇
网友评论