Created
January 25, 2022 10:44
-
-
Save itsMapleLeaf/b498d7656306797f55a651d731e37e4e to your computer and use it in GitHub Desktop.
maybe
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
export class Maybe<Value> { | |
constructor(private readonly value: Value | undefined | null) {} | |
static of<T>(value: T): Maybe<T> { | |
return new Maybe(value) | |
} | |
static empty<T>(): Maybe<T> { | |
return new Maybe<T>(undefined) | |
} | |
map<Output>(transform: (value: Value) => Output): Maybe<Output> { | |
return this.value == undefined | |
? Maybe.empty() | |
: Maybe.of(transform(this.value)) | |
} | |
tryMap<Output, ErrorValue>( | |
transform: (value: Value) => Output, | |
onError: (error: unknown) => ErrorValue, | |
): Maybe<Output | ErrorValue> { | |
try { | |
return this.map(transform) | |
} catch (error) { | |
return Maybe.of(onError(error)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment