Skip to content

Instantly share code, notes, and snippets.

@kylecorbelli
Last active June 22, 2018 14:46
Show Gist options
  • Save kylecorbelli/3b309e6660e600fe64c330b4fba07cf0 to your computer and use it in GitHub Desktop.
Save kylecorbelli/3b309e6660e600fe64c330b4fba07cf0 to your computer and use it in GitHub Desktop.
import { curry } from 'ramda'
function maybeMap<A, B> (f: (val: A) => B, m: Maybe<A>): Maybe<B> {
switch (m.type) {
case MaybeType.Nothing:
return Nothing()
case MaybeType.Just:
return Just(f(m.value))
}
}
function maybeAndThen<A, B> (f: (val: A) => Maybe<B>, m: Maybe<A>): Maybe<B> {
switch (m.type) {
case MaybeType.Nothing:
return Nothing()
case MaybeType.Just:
return f(m.value)
}
}
function maybeOf<T> (value: T): Maybe<T> {
return value === undefined || value === null
? Nothing()
: Just(value)
}
function maybeWithDefault<T> (defaultVal: T, m: Maybe<T>): T {
switch (m.type) {
case MaybeType.Nothing:
return defaultVal
case MaybeType.Just:
return m.value
}
}
export const Maybe = {
andThen: curry(maybeAndThen),
map: curry(maybeMap),
of: maybeOf,
withDefault: curry(maybeWithDefault),
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment