Created
October 7, 2012 18:13
-
-
Save co1rowjp/3849125 to your computer and use it in GitHub Desktop.
Typescript Either
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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