Created
March 29, 2018 19:51
-
-
Save bradcypert/c2d69e6a77260c3af7d645b39aadde12 to your computer and use it in GitHub Desktop.
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
abstract class Optionable<T> { | |
abstract value: T; | |
abstract get<T>(): any; | |
abstract getOrElse<U>(v: U): T | U; | |
abstract isEmpty(): boolean; | |
abstract isDefined(): boolean; | |
fold<B>(empty: () => B, nonEmpty: (value: any) => B): B { | |
if (this.isEmpty()) { | |
return empty(); | |
} | |
else { | |
return nonEmpty(this.value); | |
} | |
} | |
} | |
class None extends Optionable<null> { | |
value = null; | |
get() { | |
return null; | |
} | |
getOrElse<T>(v: T): T { | |
return v; | |
} | |
isEmpty(): boolean { | |
return true; | |
} | |
isDefined(): boolean { | |
return false; | |
} | |
} | |
class Optional<T> extends Optionable<T> { | |
constructor(public value: T) { | |
super(); | |
} | |
isEmpty(): boolean { | |
if (this.value === undefined || this.value === null) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
isDefined(): boolean { | |
return !this.isEmpty(); | |
} | |
get(): T | null { | |
if (this.value) { | |
return this.value; | |
} | |
return null; | |
} | |
getOrElse<U>(value: U): T | U { | |
if (this.value) { | |
return this.value; | |
} | |
return value; | |
} | |
} | |
function some<T>(value: T): None | Optional<T> { | |
if (value === null || value === undefined) { | |
return new None(); | |
} else { | |
return new Optional<T>(value) | |
} | |
} | |
let shouldBeNone = some(null); | |
let shouldBeOptional = some(1234); | |
console.log(shouldBeOptional.get()); | |
console.log(shouldBeOptional.getOrElse("foo")) | |
console.log(shouldBeOptional.isDefined()) | |
console.log(shouldBeOptional.isEmpty()) | |
console.log(shouldBeOptional.fold( | |
() => 0, | |
(value) => value * 2) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment