Skip to content

Instantly share code, notes, and snippets.

@mgdelacroix
Created June 14, 2016 14:54
Show Gist options
  • Save mgdelacroix/f66b73fefe293027b0d91c98abed18a4 to your computer and use it in GitHub Desktop.
Save mgdelacroix/f66b73fefe293027b0d91c98abed18a4 to your computer and use it in GitHub Desktop.
const NoSuchElementException = new Error("No such element exception");
class Optional<T> {
value: T;
constructor(value: T) {
this.value = value;
}
static empty() {
return new Optional(null);
}
static of(value) {
return new Optional(value);
}
get(): T {
if (!this.value) {
throw NoSuchElementException;
} else {
return this.value;
}
}
isPresent(): boolean {
return (this.value !== undefined && this.value !== null);
}
}
function div(a: number, b: number): Optional<number> {
if (b === 0) {
return Optional.empty();
} else {
return Optional.of(a/b);
}
}
let result: Optional<number> = div(3, 1);
if (result.isPresent()) {
console.log(`Everytihng OK: ${result.get()}`);
} else {
console.log("There is no value");
}
@mgdelacroix
Copy link
Author

Based on Java Optional

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment