Skip to content

Commit

Permalink
Support empty otherwise
Browse files Browse the repository at this point in the history
  • Loading branch information
JAForbes committed Feb 17, 2024
1 parent b8e77e9 commit ffcbaaf
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 13 deletions.
16 changes: 14 additions & 2 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ type Otherwise<D extends Definition> = {
}
}

type OtherwiseEmpty<D extends Definition> = {
otherwise: <T>() => (fn: () => T) => {
[k in keyof D]: () => T
}
}

type InternalInstance<
N extends string,
D extends Definition,
Expand All @@ -62,7 +68,8 @@ export type Superoute<N extends string, D extends Definition> = Constructors<
API<N, D> &
RouteIs<N, D> &
RouteGet<N, D> &
Otherwise<D>;
Otherwise<D> &
OtherwiseEmpty<D>;

export type RouteIs<N extends string, D extends Definition> = {
[Key in keyof D as Is<Key extends string ? Key : never>]: (
Expand Down Expand Up @@ -226,7 +233,12 @@ export function type<N extends string, D extends Definition>(
fromPathSafe,
matchOr,
match,
otherwise
otherwise: (...args: any[]) => {
if (args.length === 0) {
return otherwise(Object.keys(routes))
}
return otherwise(args[0])
}
};

for (const [tag, of] of Object.entries(routes)) {
Expand Down
37 changes: 26 additions & 11 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,32 @@ test("index: match", () => {
assert.equal(f(Example.C({ c_id: "100" })), 100);
assert.equal(f(Example.C({})), 0);

const _ = Example.otherwise(["B", "C"]);

const g = (r: superouter.Instance<typeof Example>) =>
Example.match(r, {
A: () => 1,
..._(() => -1),
});

assert.equal(g(Example.A({ a_id: "cool" })), 1);
assert.equal(g(Example.B({ b_id: "cool" })), -1);
assert.equal(g(Example.C({ c_id: "cool" })), -1);
{
const _ = Example.otherwise(["B", "C"]);

const g = (r: superouter.Instance<typeof Example>) =>
Example.match(r, {
A: () => 1,
..._(() => -1),
});

assert.equal(g(Example.A({ a_id: "cool" })), 1);
assert.equal(g(Example.B({ b_id: "cool" })), -1);
assert.equal(g(Example.C({ c_id: "cool" })), -1);
}
{
const _ = Example.otherwise();

const g = (r: superouter.Instance<typeof Example>) =>
Example.match(r, {
..._(() => -1),
A: () => 1,
});

assert.equal(g(Example.A({ a_id: "cool" })), 1);
assert.equal(g(Example.B({ b_id: "cool" })), -1);
assert.equal(g(Example.C({ c_id: "cool" })), -1);
}
});

test("index: silly", () => {
Expand Down

0 comments on commit ffcbaaf

Please sign in to comment.