Skip to content

Instantly share code, notes, and snippets.

@Ephasme
Last active June 16, 2018 10:43
Show Gist options
  • Save Ephasme/4ad02f05079a694201922bf949bf731f to your computer and use it in GitHub Desktop.
Save Ephasme/4ad02f05079a694201922bf949bf731f to your computer and use it in GitHub Desktop.
export type Unsafe<T> = Error | T;
export function match<T, TResult>(input: Unsafe<T>, succ: (t: T) => TResult, err: (err: Error) => TResult): TResult {
if (input instanceof Error) {
return err(input);
}
return succ(input as T);
}
export function matcher<T>(input: Unsafe<T>): IMatcher<T> {
return new Matcher(input);
}
interface IRightMatcherContext<TResult> {
left(act: (err: Error) => TResult): TResult;
}
class RightMatcherContext<T, TResult> implements IRightMatcherContext<TResult> {
private right: (t: T) => TResult;
private input: Unsafe<T>;
constructor(input: Unsafe<T>, right: (t: T) => TResult) {
this.right = right;
this.input = input;
}
public left(act: (err: Error) => TResult): TResult {
return match(this.input, this.right, act);
}
}
interface IMatcher<T> {
ifLeft(act: (err: Error) => void): void;
ifRight(act: (t: T) => void): void;
right<TResult>(act: (t: T) => TResult): RightMatcherContext<T, TResult>;
}
class Matcher<T> implements IMatcher<T> {
private input: Unsafe<T>;
constructor(input: Unsafe<T>) {
this.input = input;
}
public ifLeft(act: (err: Error) => void): void {
if (this.input instanceof Error) {
act(this.input);
}
}
public ifRight(act: (t: T) => void): void {
if (!(this.input instanceof Error)) {
act(this.input as T);
}
}
public right<TResult>(act: (t: T) => TResult): RightMatcherContext<T, TResult> {
throw new Error("Method not implemented.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment