Skip to content

Instantly share code, notes, and snippets.

@nicolas-zozol
Created September 12, 2019 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolas-zozol/ad7e04fdc746054f10bd2e75309f88e4 to your computer and use it in GitHub Desktop.
Save nicolas-zozol/ad7e04fdc746054f10bd2e75309f88e4 to your computer and use it in GitHub Desktop.
Optional in typecript
export class Optional<T> {
constructor(public value:T) {
}
isPresent():boolean {
return this.value !== null && this.value !== undefined;
}
map(bindCall):Optional<T> {
if (this.isPresent()) {
return Optional.someOrNone(bindCall(this.value));
} else {
return this;
}
}
flatMap(bindCall) {
if (this.isPresent()) {
return bindCall(this.value);
} else {
return this;
}
}
filter(f: (T)=>boolean) {
if (this.isPresent() && f(this.value)) {
return this;
}
// equivalent of return none() without cyclic creation
// eslint : no-use-before-define
return Optional.none();
}
get():T {
if (!this.isPresent()){
throw 'Accessing empty value';
}
return this.value;
}
orElse(value:T):T {
if (this.isPresent()) {
return this.value;
} else {
return value;
}
}
orLazyElse(value:()=>T):T {
if (this.isPresent()) {
return this.value;
} else {
return value();
}
}
static of(value){
return new Optional(value);
}
static none(){
return new Optional(null);
}
static someOrNone(value){
if (value === undefined || value === null){
return Optional.none();
}
return new Optional(value);
}
}
@nicolas-zozol
Copy link
Author

Could be improved by using a symbol("empty") instead of null or undefined

@nicolas-zozol
Copy link
Author

const findUsers = ()=> return Optional.none()

return findUsers().orElse(johnDoe)

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