Skip to content

Instantly share code, notes, and snippets.

@maxired
Last active January 16, 2025 09:28
Show Gist options
  • Select an option

  • Save maxired/1b319f6c2fb9c196f41a1cf43484e63e to your computer and use it in GitHub Desktop.

Select an option

Save maxired/1b319f6c2fb9c196f41a1cf43484e63e to your computer and use it in GitHub Desktop.
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