Skip to content

Instantly share code, notes, and snippets.

@themaxhero
Last active October 28, 2021 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save themaxhero/f591fc5acaa9ecbc8585e78ed8c7c956 to your computer and use it in GitHub Desktop.
Save themaxhero/f591fc5acaa9ecbc8585e78ed8c7c956 to your computer and use it in GitHub Desktop.
type Result<T> = {type: "ok", data: T} | {type: "error", reason: string};
export const ok = <T = unknown>(data: T): Result<T> => {
return {type: "ok", data };
};
export const error = <T = unknown>(reason: string): Result<T> => {
return {type: "error", reason};
};
export const isOk = <T = unknown>(r: Result<T>): boolean => {
if (r.type !== "error")
return true;
return false;
};
export const isError = <T = unknown>(r: Result<T>): boolean => {
if (r.type === "error")
return true;
return false;
};
export const map = <T = unknown, U = unknown>(r: Result<T>, fn: (v: T) => U): Result<U> => {
switch(r.type) {
case "ok":
return {type: "ok", data: fn(r.data)};
case "error":
return r;
}
};
export const chain = <T = unknown, U = unknown>(r: Result<T>, fn: (v: T) => Result<U>): Result<U> => {
switch(r.type) {
case "ok":
return fn(r.data);
case "error":
return r;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment