⚡ Index dispatch with the raw shape key
String(shape) defeats V8's numeric-key fast path (measured ~2x on number-keyed dispatch). JS already coerces boolean/null/undefined to the same property key, so assert shape to string | number and index directly. The assertion is TS2538-only; the facade keeps it sound. Needs a source no-unsafe-type-assertion disable, next to the existing one.
This commit is contained in:
1 parent
1ad19ba308
commit
80d498e4f4
2 files changed
+15
-7
No files matched your search
@@ -106,9 +106,11 @@ offers `true`, `false`, `null`, `undefined` by name (verified over LSP).
|
||||
|
||||
#### Why
|
||||
|
||||
- Runtime dispatch is unchanged in effect: `handlers[true]` already coerces to
|
||||
`"true"`. `dispatch` wraps the index in `String()` only because TypeScript
|
||||
forbids indexing with `boolean`/`null`/`undefined` (`TS2538`).
|
||||
- Runtime dispatch indexes with the raw `shape`; `handlers[true]` coerces to
|
||||
`"true"` at runtime exactly as `String` would. The `shape as string | number`
|
||||
assertion only placates `TS2538` and buys the number fast path (an explicit
|
||||
`String()` defeats V8's numeric-key path: measured ~2× on number-keyed
|
||||
dispatch).
|
||||
- `symbol`/`bigint`/`NaN`/`-0` are rejected, and a member colliding with its
|
||||
stringification is unguarded: user-facing, stated once in
|
||||
[README § Caveats](../README.md#caveats).
|
||||
+10
-4
@@ -109,11 +109,17 @@ type HandlerMap = Record<string | number, UnaryFn<never, unknown> | undefined>;
|
||||
const dispatch =
|
||||
(handlers: HandlerMap, fallback?: UnaryFn<never, unknown>) =>
|
||||
(shape: Matchable): unknown =>
|
||||
// `handlers[true]` already coerces to the `"true"` property at
|
||||
// runtime; `String` is here only because TypeScript forbids
|
||||
// indexing with `boolean`/`null`/`undefined` (TS2538).
|
||||
// `handlers[true]` already coerces to the `"true"` property at runtime,
|
||||
// identical to `handlers[String(shape)]`, so indexing with `shape`
|
||||
// directly is sound: `shape` is a facade-checked universe member and
|
||||
// `PatternKey` only ever produces valid property keys. The assertion is
|
||||
// needed solely because TypeScript forbids indexing with
|
||||
// `boolean`/`null`/`undefined` (TS2538); it buys the number fast path.
|
||||
(
|
||||
handlers[String(shape)] ??
|
||||
handlers[
|
||||
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
||||
shape as string | number
|
||||
] ??
|
||||
fallback ??
|
||||
(() => {
|
||||
throw new Error(`Unhandled shape: ${String(shape)}`);
|
||||
|
||||
Reference in new issue
Block a user