js monad 函数式编程

import { curry } from 'ramda';

export class Either {
  _value = null

  // Either类型的构造函数,接收一个异常或合法的值(主右的)
  constructor (value) {
    this._value = value;
  }

  get value () {
    return this._value;
  }

  static left (a) {
    return new Left(a);
  }

  static right (a) {
    return new Right(a);
  }

  // 若值非法则返回Left,否则返回Right
  static fromNullOrUndefined (val) {
    return (val !== null && val !== undefined) ? Either.right(val) : Either.left(val);
  }

  // 创建一个包含值的Right实例
  static of (a) {
    return Either.right(a);
  }
}

class Left extends Either {
  // 通过映射函数对Right结构中的值进行变换,对Left不进行任何操作
  map () {
    return this;
  }

  getOrElse (other) {
    return other;
  }

  // 将给定函数应用于Left值,不对Right进行任何操作
  orElse (f) {
    return f(this.value);
  }

  // 将给定函数应用于Right值并返回其结果,不对Left进行任何操作,
  chain () {
    return this;
  }

  // 如果Left,抛出异常
  getOrElseThrow (a) {
    throw new Error(a);
  }

  filter () {
    return this;
  }

  toString () {
    return `Either.left(${this.value})`;
  }
}

class Right extends Either {
  map (f) {
    return Either.of(f(this.value));
  }

  // Right情况,不做处理
  getOrElse () {
    return this.value;
  }

  orElse () {
    return this.value;
  }

  chain (f) {
    console.log(f, this.value, 'datadata')
    return f(this.value);
  }

  // 返回合法值
  getOrElseThrow () {
    return this.value;
  }

  filter (f) {
    console.log(f(this.value), 'f(this.value)', this.value);
    return Either.fromNullOrUndefined(f(this.value) ? this.value : null);
  }

  toString () {
    return `Either.right(${this.value})`;
  }
}

export const map = curry((f, container) => {
  return container.map(f);
});

export const chain = curry((f, container) => {
  console.log(container);
  return container.chain(f);
});

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值