Last active
October 28, 2021 09:30
-
-
Save themaxhero/f591fc5acaa9ecbc8585e78ed8c7c956 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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