Skip to content

Instantly share code, notes, and snippets.

@SekiT
Created July 7, 2021 06:16
Show Gist options
  • Save SekiT/3446aa4f46ad922909a75ed4ddf47974 to your computer and use it in GitHub Desktop.
Save SekiT/3446aa4f46ad922909a75ed4ddf47974 to your computer and use it in GitHub Desktop.
class Maybe {
constructor(isJust, value) {
this.isJust = isJust
if (isJust) {
this.value = value
}
}
static just(value) {
return new Maybe(true, value)
}
static nothing = new Maybe(false)
map(fun) {
return this.isJust ? new Maybe(true, fun(this.value)) : this
}
static pure = Maybe.just
ap(mx) {
return this.isJust ? mx.map(this.value) : this
}
bind(fun) {
return this.isJust ? fun(this.value) : this
}
static do(generatorFunction) {
const generator = generatorFunction()
const doImpl = (unwrappedValue) => {
const { done, value } = generator.next(unwrappedValue)
return done ? value : value.bind(doImpl)
}
return doImpl(undefined)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment