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);
});
js monad 函数式编程
最新推荐文章于 2024-09-14 18:52:56 发布
这篇文章介绍了如何使用ramda库来实现Either模式,Either是一个在函数式编程中用于处理可能的错误或异常的数据类型。它有两个子类Left和Right,分别代表错误和正常值。文章详细展示了Either类的构造函数、静态方法如fromNullOrUndefined、of,以及Left和Right的map、orElse、chain等方法的实现。
摘要由CSDN通过智能技术生成