Tools.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import {pinyin} from "pinyin-pro";
  2. class Tools {
  3. private static instance: Tools;
  4. static getInstance() {
  5. if (!this.instance) {
  6. this.instance = new Tools();
  7. }
  8. return this.instance;
  9. }
  10. /**
  11. * 把list结构转成 map 首字母结构
  12. * @param {Object} list
  13. */
  14. listToMap(list: any[]) {
  15. let map = new Map();
  16. let reg = /[A-Z]/;
  17. let other = '-';
  18. list.forEach((item, index) => {
  19. if (item && item.name) {
  20. //拼音的首字母
  21. let pyf = pinyin(item.name).substring(0, 1).toUpperCase()
  22. //不是26个字母,用-代替
  23. if (!reg.test(pyf)) {
  24. pyf = other
  25. }
  26. let tempList = map.get(pyf) ? map.get(pyf) : [];
  27. tempList.push({
  28. id: item.id,
  29. name: item.name,
  30. avatar: item.avatar,
  31. type: item.type,
  32. })
  33. map.set(pyf, tempList);
  34. }
  35. })
  36. let res = new Map();
  37. //从新排序
  38. for (let i = 0; i < 26; i++) {
  39. let n = String.fromCharCode(65 + i)
  40. let obj = map.get(n);
  41. if (obj) {
  42. res.set(n, obj)
  43. }
  44. }
  45. if (map.get(other)) {
  46. res.set(other, map.get(other))
  47. }
  48. return res;
  49. }
  50. }
  51. export default Tools.getInstance()