1
0

formatter.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * @file
  3. * Date-related formatting display method
  4. */
  5. import { format } from 'date-fns';
  6. import { strings } from '../constants';
  7. import { BaseValueType } from '../foundation';
  8. /**
  9. * Formats the displayed date text
  10. * @param {string[]|Date[]} values
  11. * @param {string} formatToken
  12. * @param {Object} groupOptions
  13. * @param {Object} locale
  14. * @returns {string}
  15. */
  16. export function formatDateValues(
  17. values: BaseValueType[],
  18. formatToken: string,
  19. {
  20. groupInnerSeparator = strings.DEFAULT_SEPARATOR_RANGE as string,
  21. groupSize = 1,
  22. groupSeparator = strings.DEFAULT_SEPARATOR_MULTIPLE as string,
  23. } = {},
  24. locale: any
  25. ) {
  26. let text = '';
  27. (groupSize <= 0 || typeof groupSize !== 'number') && (groupSize = 1);
  28. // console.log(values, formatToken, groupInnerSeparator, groupSize, groupSeparator);
  29. if (Array.isArray(values) && values.length) {
  30. const groups = [];
  31. const { length } = values;
  32. // chunk
  33. for (let i = 0; i < length; i++) {
  34. if (i % groupSize === 0) {
  35. groups.push([]);
  36. }
  37. const curArrIdx = Math.floor(i / groupSize);
  38. groups[curArrIdx].push(values[i]);
  39. }
  40. text = groups
  41. .map(arr =>
  42. arr
  43. .map(v => {
  44. if (v) {
  45. // console.log(`formatDateValues() -> formatDateValues: ${v}`);
  46. return format(v, formatToken, { locale });
  47. } else {
  48. return '';
  49. }
  50. })
  51. .join(groupInnerSeparator)
  52. )
  53. .join(groupSeparator);
  54. }
  55. return text;
  56. }