Skip to content

Commit

Permalink
perf(v5): reuse unmatched objects between branches
Browse files Browse the repository at this point in the history
  • Loading branch information
gvergnaud committed Jun 9, 2023
1 parent 4366ab0 commit 03dbfe6
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type MatchState<output> =
| { matched: true; value: output }
| { matched: false; value: undefined };

const defaultMatchState: MatchState<never> = {
const unmatched: MatchState<never> = {
matched: false,
value: undefined,
};
Expand All @@ -48,13 +48,14 @@ const defaultMatchState: MatchState<never> = {
class MatchExpression<input, output> {
constructor(
private input: input,
private state: MatchState<output> = defaultMatchState
private state: MatchState<output> = unmatched
) {}

with(...args: any[]): MatchExpression<input, output> {
if (this.state.matched) return this;

const handler = args[args.length - 1];
const handler: (selection: unknown, value: input) => output =
args[args.length - 1];

const patterns: Pattern<input>[] = [args[0]];
const predicates: ((value: input) => unknown)[] = [];
Expand Down Expand Up @@ -90,7 +91,7 @@ class MatchExpression<input, output> {
this.input
),
}
: { matched: false as const };
: unmatched;

return new MatchExpression(this.input, state);
}
Expand All @@ -107,7 +108,7 @@ class MatchExpression<input, output> {
this.input,
matched
? { matched: true, value: handler(this.input, this.input) }
: { matched: false, value: undefined }
: unmatched
);
}

Expand Down

0 comments on commit 03dbfe6

Please sign in to comment.