Created
April 13, 2016 14:07
-
-
Save mguenther/73cbf10a610f0dc29024b743a02dabc4 to your computer and use it in GitHub Desktop.
Option<T> monad for TS
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
export class Option<T> { | |
_value: T; | |
constructor(object: T) { | |
this._value = object; | |
} | |
static empty<T>(): Option<any> { | |
return new Option<T>(null); | |
} | |
static from<T>(nonNullableObject: T): Option<T> { | |
if (nonNullableObject === undefined) { | |
throw new Error('Option<T>: Given object must be non-null.'); | |
} | |
return new Option<T>(nonNullableObject); | |
} | |
static fromNullable<T>(nullableObject: T): Option<T> { | |
return new Option<T>(nullableObject); | |
} | |
isPresent(): boolean { | |
return this._value !== null; | |
} | |
map<U>(f: (input: T) => U): Option<U> { | |
if (!this.isPresent()) { | |
return Option.empty(); | |
} | |
return new Option<U>(f(this._value)); | |
} | |
getOrElse(defaultValue: T): T { | |
if (!this.isPresent()) { | |
return defaultValue; | |
} | |
return this._value; | |
} | |
ifPresent(f: (input: T) => void) { | |
if (this.isPresent()) { | |
f(this._value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment