Last active
January 16, 2025 09:28
-
-
Save maxired/1b319f6c2fb9c196f41a1cf43484e63e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| type recordsFunction<Input, Value> = (a: Input) => Value; | |
| const cases = <Key extends string | number, Value>( | |
| input: Key, | |
| cases: Record<Key, Value | recordsFunction<Key, Value>> & { default: Value | recordsFunction<Key, Value> } | |
| ) => { | |
| if (input in cases) { | |
| return typeof cases[input] === 'function' ? (cases[input] as recordsFunction<Key, Value>)(input) : cases[input]; | |
| } | |
| return typeof cases.default === 'function' ? (cases.default as recordsFunction<Key, Value>)(input) : cases.default; | |
| }; | |
| // sample code | |
| const max = (input: number) => | |
| cases(input, { | |
| 1: () => 1, | |
| 3: 6, | |
| default: 2, | |
| }); | |
| // usage | |
| console.log(max(1)); | |
| console.log(max(3)); | |
| console.log(max(10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment