Last active
May 20, 2024 14:48
-
-
Save duncan-rheaply/11aae60fb9223f185ca6ac9b5fbfd9fb 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