Created
July 13, 2019 15:20
-
-
Save flovilmart/582be4edf74e3336b83f76bbae76b872 to your computer and use it in GitHub Desktop.
TS: Optionals
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
class Optional<T> { | |
private val: T; | |
private is_none: boolean; | |
private constructor(value: T, is_none: boolean = false) { | |
this.val = value; | |
this.is_none = is_none; | |
} | |
static none<U>(): Optional<U> { | |
return new Optional(undefined, true); | |
} | |
static some<T>(value: T) { | |
return new Optional(value); | |
} | |
map<U>(handler: (obj: T) => U): Optional<U> { | |
if (!this.is_none) { | |
return Optional.none(); | |
} | |
return Optional.some(handler(this.val)); | |
} | |
} | |
let value = Optional.some("Hello"); | |
let thing = value.map((string) => { | |
return string + string; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment