Home Reference Source Test

src/match.ts

  1. import { IdentityMatcher, ObjectMatcher, PatternMatcher, StringMatcher } from './pattern-matching';
  2. import { ConstructorAbstractOrInstance } from './types';
  3.  
  4. // boolean equality matcher
  5. export function match<Output_Type>(_: boolean): {
  6.  
  7. when: (
  8. pattern: boolean,
  9. transformation: (_: boolean) => Output_Type,
  10. ) => PatternMatcher<boolean, boolean, boolean, Output_Type>,
  11. };
  12.  
  13. // number equality matcher
  14. export function match<Output_Type>(_: number): {
  15.  
  16. when: (
  17. pattern: number,
  18. transformation: (_: number) => Output_Type,
  19. ) => PatternMatcher<number, number, number, Output_Type>,
  20. };
  21.  
  22. // symbol equality matcher
  23. export function match<Output_Type>(_: symbol): {
  24.  
  25. when: (
  26. pattern: symbol,
  27. transformation: (_: symbol) => Output_Type,
  28. ) => PatternMatcher<symbol, symbol, symbol, Output_Type>,
  29. };
  30.  
  31. // string equality and regexp matcher
  32. export function match<Output_Type>(_: string): {
  33. when: (
  34. pattern: string | RegExp,
  35. transformation: (_: string) => Output_Type,
  36. ) => PatternMatcher<string, string | RegExp, string, Output_Type>,
  37. };
  38.  
  39. // type matcher
  40. export function match<Input_Type, Output_Type>(_: Input_Type): {
  41.  
  42. when: <MT extends Input_Type>(
  43. pattern: ConstructorAbstractOrInstance<MT>,
  44. transformation: (v: MT) => Output_Type,
  45. ) => PatternMatcher<Input_Type, ConstructorAbstractOrInstance<Input_Type>, Input_Type, Output_Type>,
  46. };
  47.  
  48. /**
  49. * @experimental
  50. *
  51. * @param value
  52. * @returns {PatternMatcher<any, any, any, any>}
  53. */
  54. export function match(value: any): PatternMatcher<any, any, any, any> { // eslint-disable-line @typescript-eslint/explicit-module-boundary-types
  55. switch (true) {
  56. case typeof value === 'string':
  57. return new StringMatcher(value as string);
  58. case typeof value === 'object':
  59. return new ObjectMatcher(value);
  60. default:
  61. return new IdentityMatcher(value);
  62. }
  63. }