|
| 1 | +class InlineSwitch<T, R = never, E = undefined> { |
| 2 | + private cases = new Map<T, () => any>(); |
| 3 | + private defaultCase?: () => any; |
| 4 | + |
| 5 | + constructor(private readonly value: T) { } |
| 6 | + |
| 7 | + // Method to add a case |
| 8 | + case<U>(caseValue: T, result: () => U): InlineSwitch<T, R | U> { |
| 9 | + this.cases.set(caseValue, result); |
| 10 | + return this as any; |
| 11 | + } |
| 12 | + |
| 13 | + // Method to set the default case |
| 14 | + default<U>(result: () => U): Omit<InlineSwitch<T, R | U, never>, 'default'> { |
| 15 | + if (this.defaultCase) { |
| 16 | + throw new Error("Default case already set."); |
| 17 | + } |
| 18 | + this.defaultCase = result; |
| 19 | + return this as any; |
| 20 | + } |
| 21 | + |
| 22 | + // Method to execute the switch |
| 23 | + execute(): R | E { |
| 24 | + const result = this.cases.get(this.value); |
| 25 | + if (result) { |
| 26 | + return result(); |
| 27 | + } |
| 28 | + |
| 29 | + if (this.defaultCase) { |
| 30 | + return this.defaultCase(); |
| 31 | + } |
| 32 | + |
| 33 | + return undefined as any; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Creates a new InlineSwitch instance for given value. This utility function |
| 39 | + * facilitates a fluent interface for conditional logic based on the value provided, |
| 40 | + * allowing for a more readable and expressive alternative to traditional switch |
| 41 | + * statements or if-else chains. The InlineSwitch class supports adding cases |
| 42 | + * with `.case()` method calls and optionally setting a default case with `.default()`. |
| 43 | + * The `.execute()` method evaluates the cases against the value and returns the |
| 44 | + * result of the matching case or the default case, if provided. |
| 45 | + * |
| 46 | + * @param value The value to be matched against the defined cases in the InlineSwitch instance. |
| 47 | + * @returns A new instance of InlineSwitch configured with the provided value. |
| 48 | + * |
| 49 | + * @example |
| 50 | + * // Using inlineSwitch to determine fruit colors. |
| 51 | + * const fruitColor = inlineSwitch('apple') |
| 52 | + * .case('apple', () => 'red') |
| 53 | + * .case('banana', () => 'yellow') |
| 54 | + * .case('orange', () => 'orange') |
| 55 | + * .default(() => 'unknown color') |
| 56 | + * .execute(); |
| 57 | + * |
| 58 | + * console.log(fruitColor); // Outputs: 'red' |
| 59 | + * |
| 60 | + * @example |
| 61 | + * // Using inlineSwitch with mixed return types and a default case. |
| 62 | + * const processedValue = inlineSwitch('kiwi') |
| 63 | + * .case('apple', () => 42) |
| 64 | + * .case('banana', () => true) |
| 65 | + * .case('orange', () => 'orange') |
| 66 | + * .default(() => null) |
| 67 | + * .execute(); |
| 68 | + * |
| 69 | + * console.log(processedValue); // Outputs: null |
| 70 | + */ |
| 71 | +export function inlineSwitch<T>(value: T) { |
| 72 | + return new InlineSwitch(value); |
| 73 | +} |
0 commit comments