Last active
April 7, 2025 16:52
-
-
Save CHBaker/22213410c5145a089e1d2789fe825eac to your computer and use it in GitHub Desktop.
Strong Typed Switch Functional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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