Skip to content

Instantly share code, notes, and snippets.

@mrFunkyWisdom
Created January 3, 2019 18:05
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 mrFunkyWisdom/588a1f5c2db75a5538d2becb6b97b621 to your computer and use it in GitHub Desktop.
Save mrFunkyWisdom/588a1f5c2db75a5538d2becb6b97b621 to your computer and use it in GitHub Desktop.
Java Optional type with JavaScript
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;
@mrFunkyWisdom
Copy link
Author

example how to use an Optional type

const toUpper = str => str.toUpperCase()

const textScraper = elem => 
   Optional
      .of(elem.match(/<p>([\s\S]*)?<\/p>/i))
      .map(elem => elem[1])
           
 const someValuee = textScraper('<p>some text</p>')
    .map(str => str.trim())
    .map(va => va + " here")
    .flatMap(str => new Optional.of(toUpper(str)))
    .map(toUpper)
    .getOrElse(() => 'there is no text to scrape')

console.log(someValuee)
result > SOME TEXT HERE

and if we change this line

const someValuee = textScraper('<p>some text</p>')

to

const someValuee = textScraper('<div>some text</div>')

result will be

result > there is no text to scrape

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