Skip to content

Instantly share code, notes, and snippets.

@WhoAteDaCake
Last active May 22, 2019 15:05
Show Gist options
  • Save WhoAteDaCake/a040ba7a5c6ece85eda69bab9515d69e to your computer and use it in GitHub Desktop.
Save WhoAteDaCake/a040ba7a5c6ece85eda69bab9515d69e to your computer and use it in GitHub Desktop.
Result type
type Change<V, V2> = (item: V) => V2;
type Empty = null;
const empty: Empty = null;
export class Result<E, V> {
value: V | Empty;
error: E | Empty;
static EMPTY = empty;
static fromArr<E, V>(items: [E | Empty, V | Empty]) {
return new Result(items[0], items[1]);
}
static errorMap<V, E, E2>(fn: Change<E, E2>) {
return (r: Result<E, V>) => r.errorMap(fn);
}
static valueMap<V, V2, E>(fn: Change<V, V2>) {
return (r: Result<E, V>) => r.valueMap(fn);
}
constructor(error: E, value: V) {
this.error = error;
this.value = value;
}
errorMap<E2>(fn: Change<E, E2>): Result<E2, Empty> | Result<Empty, V> {
if (this.error !== Result.EMPTY) {
return new Result(fn(this.error), Result.EMPTY);
}
return new Result(Result.EMPTY, this.value);
}
valueMap<V2>(fn: Change<V, V2>): Result<Empty, V2> | Result<E, Empty> {
if (this.value !== Result.EMPTY) {
return new Result(Result.EMPTY, fn(this.value));
}
return new Result(this.error, Result.EMPTY);
}
ifValue(fn: Change<V, void>) {
if (this.value !== Result.EMPTY) {
fn(this.value);
}
return this;
}
ifError(fn: Change<E, void>) {
if (this.error !== Result.EMPTY) {
fn(this.error);
}
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment