Created
September 12, 2019 14:30
-
-
Save nicolas-zozol/ad7e04fdc746054f10bd2e75309f88e4 to your computer and use it in GitHub Desktop.
Optional in typecript
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 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); | |
} | |
} |
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
Could be improved by using a symbol("empty") instead of null or undefined