Last active
May 22, 2019 15:05
-
-
Save WhoAteDaCake/a040ba7a5c6ece85eda69bab9515d69e to your computer and use it in GitHub Desktop.
Result type
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 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