common_util.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Zhong
  6. * @date 2019/11/12
  7. * @version
  8. */
  9. ((factory) => {
  10. if (typeof module !== 'undefined') {
  11. module.exports = factory();
  12. } else {
  13. window.commonUtil = factory();
  14. }
  15. })(() => {
  16. function isDef(val) {
  17. return typeof val !== 'undefined' && val !== null;
  18. }
  19. function isEmptyVal(val) {
  20. return val === null || val === undefined || val === '';
  21. }
  22. // 将树数据排序好
  23. function getSortedTreeData(rootID, items) {
  24. return sortSameDedth(rootID, items).reverse();
  25. function sortSameDedth(parentID, items) {
  26. const sameDepthItems = items.filter(item => item.ParentID === parentID);
  27. if (!sameDepthItems.length) {
  28. return [];
  29. }
  30. const NextIDMapping = {};
  31. sameDepthItems.forEach(item => NextIDMapping[item.NextSiblingID] = item);
  32. let curItem = sameDepthItems.length > 1 ? sameDepthItems.find(item => item.NextSiblingID === -1) : sameDepthItems[0];
  33. const sorted = [];
  34. while (curItem) {
  35. sorted.push(...sortSameDedth(curItem.ID, items));
  36. sorted.push(curItem);
  37. curItem = NextIDMapping[curItem.ID] || null;
  38. }
  39. return sorted;
  40. }
  41. }
  42. // 给数值加上分割
  43. // eg: 1234567.00 => 1,234,567.00
  44. function standardNumber(str) {
  45. if (typeof str === 'number') {
  46. str = String(str);
  47. }
  48. if (typeof str !== 'string') {
  49. return '';
  50. }
  51. const [intPart, decimalPart] = str.split('.');
  52. // 给整数部分加上“,”
  53. const temp = [];
  54. for (let i = intPart.length - 1, j = 1; i >= 0; i--, j++) {
  55. temp.push(intPart[i]);
  56. if (j !==0 && j % 3 === 0 && i - 1 >= 0) {
  57. temp.push(',');
  58. }
  59. }
  60. const standardIntPart = temp.reverse().join('');
  61. return `${standardIntPart}${decimalPart ? '.' + decimalPart : ''}`;
  62. }
  63. return {
  64. isDef,
  65. isEmptyVal,
  66. getSortedTreeData,
  67. standardNumber,
  68. };
  69. });