Skip to content

Instantly share code, notes, and snippets.

@ileitch
Created June 18, 2020 14:59
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 ileitch/56263001c8b3633826ec60b1db6a28a9 to your computer and use it in GitHub Desktop.
Save ileitch/56263001c8b3633826ec60b1db6a28a9 to your computer and use it in GitHub Desktop.
export type Result<T, E> = Success<T, E> | Failure<T, E>
export const success = <T, E>(value: T): Success<T, E> => new Success(value)
export const failure = <T, E>(error: E): Failure<T, E> => new Failure(error)
export class Success<T, E> {
constructor(readonly value: T) {}
map<A>(transform: (t: T) => A): Result<A, E> {
return success(transform(this.value))
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
mapFailure<U>(_transform: (e: E) => U): Result<T, U> {
return success(this.value)
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
match = <A>(success: (t: T) => A, _failure: (e: E) => A): A => {
return success(this.value)
}
}
export class Failure<T, E> {
constructor(readonly error: E) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
map<A>(_transform: (t: T) => A): Result<A, E> {
return failure(this.error)
}
mapFailure<U>(transform: (e: E) => U): Result<T, U> {
return failure(transform(this.error))
}
match = <A>(_success: (t: T) => A, failure: (e: E) => A): A => {
return failure(this.error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment