Skip to content

Instantly share code, notes, and snippets.

@CHBaker
Last active April 7, 2025 16:52
Show Gist options
  • Save CHBaker/22213410c5145a089e1d2789fe825eac to your computer and use it in GitHub Desktop.
Save CHBaker/22213410c5145a089e1d2789fe825eac to your computer and use it in GitHub Desktop.
Strong Typed Switch Functional
const getTwoColIndexByHorizontalRendering = switchCase<string, number | null>({
'2 Column - 1 Column': 0,
'1 Column - 2 Column': 1,
})(null);
// Examples
getTwoColIndexByHorizontalRendering('2 Column - 1 Column'); // returns 0
getTwoColIndexByHorizontalRendering('1 Column - 2 Column'); // returns 1
getTwoColIndexByHorizontalRendering('unknown layout'); // returns null
const executeIfFunction = <T>(f: T | (() => T)): T =>
typeof f === 'function' ? (f as () => T)() : f;
const switchf =
<ValueType>(cases: { [key: PropertyKey]: ValueType }) =>
(defaultCase: ValueType) =>
(key: PropertyKey) =>
cases.hasOwnProperty(key) ? cases[key] : defaultCase;
export const switchCase =
<KeyType extends PropertyKey, ValueType>(
cases: { [key in KeyType]: ValueType }
) =>
(defaultCase: ValueType) =>
(key: KeyType) =>
executeIfFunction<ValueType>(
switchf<ValueType>(cases)(defaultCase)(key)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment