Created
January 3, 2019 18:05
-
-
Save mrFunkyWisdom/588a1f5c2db75a5538d2becb6b97b621 to your computer and use it in GitHub Desktop.
Java Optional type with JavaScript
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
class OptionalType { | |
constructor (value){ | |
this.value = value | |
} | |
get() { | |
return this.value | |
} | |
getOrElse(orElse) { | |
const elseVal = orElse instanceof Function ? orElse() : orElse | |
return this.isDefined() ? this.value : elseVal; | |
} | |
map(mapFn) { | |
return this.isDefined() ? new of(mapFn(this.value)) : empty(); | |
} | |
flatMap(mapFn) { | |
return this.isDefined() ? mapFn(this.value) : empty() | |
} | |
isDefined () { | |
return (this.value !== undefined); | |
} | |
} | |
const empty = () => | |
new OptionalType() | |
const of = value => | |
(value === undefined || value === null) ? | |
new empty() : | |
new OptionalType(value) | |
const Optional = { | |
of, | |
empty | |
} | |
export default Optional; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example how to use an Optional type
and if we change this line
to
result will be