Last active
February 6, 2018 15:00
-
-
Save fsubal/b2aacdae1b3419efbcb1092f0151bba4 to your computer and use it in GitHub Desktop.
Option<T> type for Flowtype
This file contains hidden or 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
/** @flow */ | |
class Some<T>{ | |
value: T; | |
constructor(v: T) { | |
this.value = v; | |
} | |
unwrap(): T { | |
return this.value; | |
} | |
isNone(): boolean { | |
return false; | |
} | |
isSome(): boolean { | |
return true; | |
} | |
map<U>(fnc: (v: T) => U): Option<U> { | |
return new Some(fnc(this.value)); | |
} | |
flatMap<U>(fnc: (v: T) => U): U { | |
return fnc(this.value); | |
} | |
toArray(): T[] { | |
return [this.value]; | |
} | |
orElse(v: any): Some<T> { | |
return this; | |
} | |
getOrElse(v: any): T { | |
return this.value; | |
} | |
} | |
class None { | |
constructor() {} | |
unwrap() { | |
throw new Error('Called unwrap on none'); | |
} | |
isNone(): boolean { | |
return true; | |
} | |
isSome(): boolean { | |
return false; | |
} | |
map(): None { | |
return this; | |
} | |
flatMap(): None { | |
return this; | |
} | |
toArray(): any[] { | |
return []; | |
} | |
orElse<U>(v: U): Option<U> { | |
if (v instanceof Some) { | |
return new Some(v); | |
} else { | |
return this; | |
} | |
} | |
getOrElse<U>(v: U): U { | |
return v; | |
} | |
} | |
export type Option<T> = Some<T> | None; | |
export function some<T>(v: T) { | |
return new Some(v); | |
} | |
export const none = new None(); | |
export function wrap<T>(v: T): Option<T> { | |
if (v == null) { | |
return none; | |
} | |
return some(v); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment