Last active
January 28, 2022 22:10
-
-
Save kylecorbelli/6935ab3034ac88d3915bc2a02d783f5e to your computer and use it in GitHub Desktop.
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
import { curry } from 'ramda' | |
enum MaybeType { | |
Just = 'maybe-type__just', | |
Nothing = 'maybe-type__nothing', | |
} | |
interface Just<T> extends Readonly<{ | |
type: typeof MaybeType.Just | |
value: T | |
}> {} | |
interface Nothing extends Readonly <{ | |
type: typeof MaybeType.Nothing | |
}> {} | |
type Maybe<T> | |
= Just<T> | |
| Nothing | |
const Nothing = (): Nothing => ({ | |
type: MaybeType.Nothing, | |
}) | |
const Just = <T> (value: T): Just<T> => ({ | |
type: MaybeType.Just, | |
value, | |
}) | |
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 | |
} | |
} | |
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
Nice