Advertisement
Badal_hs_shah

Untitled

Feb 20th, 2023
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. import IData from '../interfaces/IData';
  2. import validLetters from './validLetters';
  3. import ISectionData from '../interfaces/ISectionData';
  4.  
  5. interface IAlphabetSet<T> {
  6. [key: string]: IData<T>[];
  7. }
  8.  
  9. interface IEntry<T> {
  10. title: string;
  11. data: IData<T>[];
  12. }
  13.  
  14. const getSectionData<T> = (data: IData<T>[]) => {
  15. const alphabetEntrySet: [string, IData<T>[]][] = getAlphabetEntrySet(data);
  16.  
  17. return alphabetEntrySet
  18. .map(formatEntry)
  19. .sort(sortSectionsAlphabetically)
  20. .map((section: ISectionData, index: number) => ({...section, index}));
  21. };
  22.  
  23. const getAlphabetEntrySet = (data: IData[]) => {
  24. const alphabetSet: IAlphabetSet = {};
  25.  
  26. data.forEach(item => {
  27. const letter = getItemFirstLetter(item.value);
  28.  
  29. if (!letter) {
  30. return;
  31. }
  32.  
  33. if (!alphabetSet[letter]) {
  34. alphabetSet[letter] = [];
  35. }
  36.  
  37. alphabetSet[letter].push(item);
  38. });
  39.  
  40. return Object.entries(alphabetSet);
  41. };
  42.  
  43. const getItemFirstLetter = (value: string) => {
  44. const firstChar: string = value.substring(0, 1);
  45. const isValidLetter: boolean = validLetters[firstChar.toLowerCase()];
  46.  
  47. if (isValidLetter) {
  48. return firstChar.toUpperCase();
  49. }
  50.  
  51. return '#';
  52. };
  53.  
  54. const formatEntry = (entry: [string, any[]]) => {
  55. const [title, unsortedData] = entry;
  56.  
  57. const data = unsortedData.sort((a, b) =>
  58. alphabeticComparison(a.value, b.value),
  59. );
  60.  
  61. return {title, data} as IEntry;
  62. };
  63.  
  64. const sortSectionsAlphabetically = (a: IEntry, b: IEntry) => {
  65. const {title: charA} = a;
  66. const {title: charB} = b;
  67.  
  68. const isBHash = charA !== '#' && charB === '#';
  69. if (isBHash) {
  70. return -1;
  71. }
  72.  
  73. const isAHash = charA === '#' && charB !== '#';
  74. if (isAHash) {
  75. return 1;
  76. }
  77.  
  78. return alphabeticComparison(charA, charB);
  79. };
  80.  
  81. const alphabeticComparison = (a: string, b: string) => {
  82. const aCap = a.toUpperCase();
  83. const bCap = b.toUpperCase();
  84.  
  85. if (aCap < bCap) {
  86. return -1;
  87. }
  88.  
  89. if (aCap > bCap) {
  90. return 1;
  91. }
  92.  
  93. return 0;
  94. };
  95.  
  96. export default getSectionData;
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement