buildLocalizeFn.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * The localize function argument callback which allows to convert raw value to
  3. * the actual type.
  4. *
  5. * @param value - The value to convert
  6. *
  7. * @returns The converted value
  8. */
  9. /**
  10. * The map of localized values for each width.
  11. */
  12. /**
  13. * The index type of the locale unit value. It types conversion of units of
  14. * values that don't start at 0 (i.e. quarters).
  15. */
  16. /**
  17. * Converts the unit value to the tuple of values.
  18. */
  19. /**
  20. * The tuple of localized era values. The first element represents BC,
  21. * the second element represents AD.
  22. */
  23. /**
  24. * The tuple of localized quarter values. The first element represents Q1.
  25. */
  26. /**
  27. * The tuple of localized day values. The first element represents Sunday.
  28. */
  29. /**
  30. * The tuple of localized month values. The first element represents January.
  31. */
  32. export function buildLocalizeFn(args) {
  33. return (value, options) => {
  34. const context = options?.context ? String(options.context) : "standalone";
  35. let valuesArray;
  36. if (context === "formatting" && args.formattingValues) {
  37. const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
  38. const width = options?.width ? String(options.width) : defaultWidth;
  39. valuesArray =
  40. args.formattingValues[width] || args.formattingValues[defaultWidth];
  41. } else {
  42. const defaultWidth = args.defaultWidth;
  43. const width = options?.width ? String(options.width) : args.defaultWidth;
  44. valuesArray = args.values[width] || args.values[defaultWidth];
  45. }
  46. const index = args.argumentCallback ? args.argumentCallback(value) : value;
  47. // @ts-expect-error - For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!
  48. return valuesArray[index];
  49. };
  50. }