MayBe 函子的作用就是可以对外部的空值情况做处理(控制副作用在允许的范围)

    1. class MayBe {
    2. static of (value) {
    3. return new MayBe(value)
    4. }
    5. constructor (value) {
    6. this._value = value
    7. }
    8. map(fn) {
    9. // 判断一下value的值是不是null和undefined,如果是就返回一个value为null的函子,如果不是就执行函数
    10. return this.isNothing() ? MayBe.of(null) : MayBe.of(fn(this._value))
    11. }
    12. // 定义一个判断是不是null或者undefined的函数,返回true/false
    13. isNothing() {
    14. return this._value === null || this._value === undefined
    15. }
    16. }
    17. const r = MayBe.of('hello world')
    18. .map(x => x.toUpperCase())
    19. console.log(r) //MayBe { _value: 'HELLO WORLD' }
    20. // 如果输入的是null,是不会报错的
    21. const rnull = MayBe.of(null)
    22. .map(x => x.toUpperCase())
    23. console.log(rnull) //MayBe { _value: null }

    但是这里有一个问题就是,如果map中间有好几步,最后返回是null,并不知道是哪一个步骤返回的。解决这个问题,需要看Either函子。