Skip to content

Instantly share code, notes, and snippets.

@co1rowjp
Created October 7, 2012 18:13
Show Gist options
  • Save co1rowjp/3849125 to your computer and use it in GitHub Desktop.
Save co1rowjp/3849125 to your computer and use it in GitHub Desktop.
Typescript Either
interface Either {
isRight: Boolean;
isLeft: Boolean;
left: LeftProjection;
right: RightProjection;
}
class Right implements Either {
isRight: Boolean = true;
isLeft: Boolean = false;
right: RightProjection;
left: LeftProjection;
constructor(a: any) {
this.right = new RightProjection(this, a)
this.left = new LeftProjection(this, a)
}
}
class Left implements Either {
isRight: Boolean = false;
isLeft: Boolean = true;
right: RightProjection;
left: LeftProjection;
constructor(a: any) {
this.right = new RightProjection(this, a)
this.left = new LeftProjection(this, a)
}
}
class RightProjection {
private a: any;
private e: Right;
constructor(e: Right, a: any) {
this.a = a
this.e = e
}
fmap (f: (any) => any): Right {
if (this.e.isRight) {
return new Right(f(this.a))
} else {
return this.e
}
}
bind (f: (any) => Either): Either {
if (this.e.isRight) {
return f(this.a)
} else {
return this.e
}
}
}
class LeftProjection {
private a: any;
private e: Left;
constructor(e: Left, a: any) {
this.a = a
this.e = e
}
fmap (f: (any) => any): Left {
if (this.e.isLeft) {
return new Left(f(this.a))
} else {
return this.e
}
}
bind (f: (any) => Either): Either {
if (this.e.isLeft) {
return f(this.a)
} else {
return this.e
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment