Skip to content

Commit

Permalink
use a weakmap for hasMatchingState
Browse files Browse the repository at this point in the history
  • Loading branch information
radium-v committed Oct 29, 2024
1 parent 5a2b61c commit 09feacb
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/web-components/src/utils/element-internals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ export function toggleState(elementInternals: ElementInternals, state: string |
elementInternals.states.delete(state);
}

/**
* A weak map to store the valid states for attributes.
* @internal
*/
const matchingStateMap = new WeakMap<Record<string, string>, Set<string>>();

/**
* Check if a given attribute value is a valid state. Attribute values are often kebab-cased, so this function converts
* the kebab-cased `state` to camelCase and checks if it exists in as a key in the `States` object.
Expand All @@ -79,8 +85,13 @@ export function hasMatchingState(States: Record<string, string> | undefined, sta
return false;
}

const camelState = state.replace(/-([a-z])/g, g => g[1].toUpperCase());
return Object.hasOwn(States, camelState);
if (matchingStateMap.has(States)) {
return matchingStateMap.get(States)!.has(state);
}

const stateSet = new Set(Object.values(States));
matchingStateMap.set(States, stateSet);
return stateSet.has(state);
}

/**
Expand Down

0 comments on commit 09feacb

Please sign in to comment.