Created
February 27, 2018 14:23
-
-
Save adhrinae/72cd4ba66243a95a697d6cf670c84429 to your computer and use it in GitHub Desktop.
Typescript Either TryOut
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
class Either { | |
protected $value; | |
static of<T>(x: T) { | |
return new Right(x); | |
} | |
constructor(x) { | |
this.$value = x; | |
} | |
fold<T>(fn: Function): T { | |
return fn(this.$value); | |
} | |
} | |
class Right<T> extends Either { | |
public type: 'right' = 'right'; | |
constructor(x: T) { | |
super(x); | |
} | |
inspect() { | |
return `Right(${this.$value})`; | |
} | |
toString() { | |
return `${this.$value}`; | |
} | |
map<U>(fn: Function): Right<U> { | |
return Either.of(fn(this.$value)); | |
} | |
} | |
class Left<T> extends Either { | |
public type: 'left' = 'left'; | |
constructor(x: T) { | |
super(x); | |
} | |
inspect() { | |
return `Left(${this.$value})`; | |
} | |
toString() { | |
return `${this.$value}`; | |
} | |
map(): Left<T> { | |
return this; | |
} | |
} | |
const either = Either.of<number>(10); | |
const calculated = either | |
.map(n => n * 10) | |
.map(n => n + 100); | |
const handleValue = (val: Left<string> | Right<number>) => { | |
if (val.type === 'left') { | |
console.error(val.fold(x => x)); | |
} | |
if (val.type === 'right') { | |
console.log('the value is ' + val); | |
} | |
} | |
// 특정 조건을 만족할 때 Left 객체를 리턴하도록 만든다 | |
const left = new Left('Hi, I am Error!'); | |
handleValue(calculated); | |
handleValue(left); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment