Skip to content

Commit

Permalink
Merge pull request #2 from joshuajaco/add-match
Browse files Browse the repository at this point in the history
Add match method
  • Loading branch information
joshuajaco committed Jul 6, 2022
2 parents cc35b7d + c0e09cf commit d3ee338
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
8 changes: 8 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ type Methods<T, E> = {
andThen: <U>(fn: (value: T) => Result<U, E>) => Result<U, E>;
or: <F>(result: Result<T, F>) => Result<T, F>;
orElse: <F>(fn: (error: E) => Result<T, F>) => Result<T, F>;
match: <U, F>(matcher: {
ok: (value: T) => U;
error: (error: E) => F;
}) => U | F;
};

type Attributes<T, E> = { ok: true; value: T } | { ok: false; error: E };
Expand Down Expand Up @@ -63,6 +67,10 @@ function createResult<T, E>(init: Attributes<T, E>): Result<T, E> {
if (init.ok) return createResult(init);
return createResult({ ok: false, error: fn(init.error) });
},
match(matcher) {
if (init.ok) return matcher.ok(init.value);
return matcher.error(init.error);
},
};
}

Expand Down
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"nyc": "^15.1.0",
"prettier": "^2.7.1",
"rimraf": "^3.0.2",
"ts-expect": "^1.3.0",
"typescript": "^4.7.4"
}
}
14 changes: 13 additions & 1 deletion test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Result } from "./index";
import assert from "assert";
import { expectType } from "ts-expect";
import { Result } from "./index";

const { ok, error, equals, from, wrap } = Result;

Expand Down Expand Up @@ -184,3 +185,14 @@ assert(equals(ok<number, number>(2).orElse(err).orElse(sq), ok(2)));
assert(equals(error<number, number>(3).orElse(sq).orElse(err), ok(9)));

assert(equals(error<number, number>(3).orElse(err).orElse(err), error(3)));

// match

assert.equal(ok(1).match({ ok: (x) => x.toString(), error: () => {} }), "1");
assert.equal(error(1).match({ ok: () => {}, error: (x) => x.toString() }), "1");

expectType<number>(ok(1).match({ ok: () => 1, error: () => 1 }));
expectType<"foo" | "bar">(ok(1).match({ ok: () => "foo", error: () => "bar" }));

// @ts-expect-error
expectType<string>(ok(1).match({ ok: () => "foo", error: () => {} }));

0 comments on commit d3ee338

Please sign in to comment.