Skip to content

Instantly share code, notes, and snippets.

@adregan
Forked from duncan-rheaply/Option.ts
Created May 20, 2024 14:48
Show Gist options
  • Save adregan/5d55084ff65d9a4cb936b2ab397e205c to your computer and use it in GitHub Desktop.
Save adregan/5d55084ff65d9a4cb936b2ab397e205c to your computer and use it in GitHub Desktop.
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