Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created January 25, 2022 10:44
Show Gist options
  • Save itsMapleLeaf/b498d7656306797f55a651d731e37e4e to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/b498d7656306797f55a651d731e37e4e to your computer and use it in GitHub Desktop.
maybe
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