-
-
Save adregan/5d55084ff65d9a4cb936b2ab397e205c 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
const _Some = Symbol("some"); | |
const _None = Symbol("none"); | |
type Some<T> = { | |
type: typeof _Some; | |
value: T; | |
}; | |
type None = { | |
type: typeof _None; | |
}; | |
export type Option<T> = Some<T> | None; | |
export const isSome = <T>(option: Option<T>): option is Some<T> => option.type === _Some; | |
export const isNone = <T>(option: Option<T>): option is None => option.type === _None; | |
export const some = <T>(value: T): Some<T> => ({ | |
type: _Some, | |
value, | |
}); | |
export const none = (): None => ({ type: _None }); | |
export const map = <T, A>(option: Option<T>, fn: (value: T) => A): Option<A> => { | |
if (isSome(option)) { | |
return some(fn(option.value)); | |
} else { | |
return none(); | |
} | |
}; | |
export const match = <T, A, B>(option: Option<T>, onSome: (value: T) => A, onNone: () => B) => | |
isSome(option) ? onSome(option.value) : onNone(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment