Advertisement
Badal_hs_shah

Untitled

Feb 20th, 2023
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 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 {
  6. [key: string]: IData[];
  7. }
  8.  
  9. interface IEntry {
  10. title: string;
  11. data: IData[];
  12. }
  13.  
  14. const getSectionData = (data: IData[]) => {
  15. const alphabetEntrySet: [string, IData[]][] = 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) => alphabeticComparison(a.value, b.value));
  58.  
  59. return { title, data } as IEntry;
  60. };
  61.  
  62. const sortSectionsAlphabetically = (a: IEntry, b: IEntry) => {
  63. const { title: charA } = a;
  64. const { title: charB } = b;
  65.  
  66. const isBHash = charA !== "#" && charB === "#";
  67. if (isBHash) {
  68. return -1;
  69. }
  70.  
  71. const isAHash = charA === "#" && charB !== "#";
  72. if (isAHash) {
  73. return 1;
  74. }
  75.  
  76. return alphabeticComparison(charA, charB);
  77. };
  78.  
  79. const alphabeticComparison = (a: string, b: string) => {
  80. const aCap = a.toUpperCase();
  81. const bCap = b.toUpperCase();
  82.  
  83. if (aCap < bCap) {
  84. return -1;
  85. }
  86.  
  87. if (aCap > bCap) {
  88. return 1;
  89. }
  90.  
  91. return 0;
  92. };
  93.  
  94. export default getSectionData;
  95.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement