1-03函子Functor

函数式编程-函子

在函数式编程中把副作用控制在可控的范围内、异常处理、异步操作等

Functor

  • 容器:包含值和值的变形关系(这个变形关系就是函数)
  • 函子:是一个特殊的容器,通过一个普通的对象来实现,该对象具有 map 方法,map 方法可以运
    行一个函数对值进行处理(变形关系)
// 一个容器,包裹一个值
class Container {
  // of 静态方法,可以省略 new 关键字创建对象
  static of(value) {
    return new Container(value);
  }

  constructor(value) {
    this._value = value;
  }

  // map 方法,传入变形关系,将容器里的每一个值映射到另一个容器
  map(fn) {
    return Container.of(fn(this._value));
  }
}

// // 测试
// let res = Container.of(2)
//   .map((x) => x + 2)
//   .map((x) => x * x);
// console.log(res);

  • 传入null undefine 的问题(副作用) 报错
// null undefine 的问题(副作用) 报错
let res1 = Container.of(null)
  .map((x) => x.toString())
console.log(res1);

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 rs1 = MayBe.of('stay hungry').map(x => x.toUpperCase());
    console.log(rs1);
    
    //传入空值
    let rs2 = MayBe.of().map(x => x.toUpperCase());
    console.log(rs2);      //  => MayBe {_value: null}    没有undefined的时候
    
  • 在 MayBe 函子中,我们很难确认是哪一步产生的空值问题 :

MayBe.of('hello world')
.map(x => x.toUpperCase())
.map(x => null)
.map(x => x.split(' '))
// => MayBe { _value: null }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值