1
0

util.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import {
  2. isNull,
  3. isUndefined,
  4. isEqual
  5. } from 'lodash';
  6. import { strings } from './constants';
  7. function getPosition(level: any, index: any) {
  8. return `${level}-${index}`;
  9. }
  10. export function isValid(val: any) {
  11. return !isNull(val) && !isUndefined(val);
  12. }
  13. export function normalizedArr(val: any) {
  14. if (!Array.isArray(val)) {
  15. return [val];
  16. } else {
  17. return val;
  18. }
  19. }
  20. /**
  21. * Traverse all the data by `treeData`.
  22. */
  23. function traverseDataNodes(treeNodes: any, callback: any) {
  24. const processNode = (node: any, ind?: any, parent?: any) => {
  25. const children = node ? node.children : treeNodes;
  26. let item: any = null;
  27. // Process node if is not root
  28. if (node) {
  29. const key = parent ? getPosition(parent.key, ind) : `${ind}`;
  30. item = {
  31. data: { ...node },
  32. ind,
  33. key,
  34. level: parent ? parent.level + 1 : 0,
  35. parentKey: parent ? parent.key : null,
  36. path: parent ? [...parent.path, key] : [key],
  37. valuePath: parent ? [...parent.valuePath, node.value] : [node.value]
  38. };
  39. callback(item);
  40. }
  41. // Process children node
  42. if (children) {
  43. children.forEach((subNode: any, subIndex: any) => {
  44. processNode(subNode, subIndex, item);
  45. });
  46. }
  47. };
  48. processNode(null);
  49. }
  50. export function convertDataToEntities(dataNodes: any) {
  51. const keyEntities: any = {};
  52. traverseDataNodes(dataNodes, (data: any) => {
  53. const { key, parentKey } = data;
  54. const entity = { ...data };
  55. keyEntities[key] = entity;
  56. // Fill children
  57. entity.parent = keyEntities[parentKey];
  58. if (entity.parent) {
  59. entity.parent.children = entity.parent.children || [];
  60. entity.parent.children.push(entity);
  61. }
  62. });
  63. return keyEntities;
  64. }
  65. export function findKeysForValues(value: any, keyEntities: any) {
  66. const valuePath = normalizedArr(value);
  67. const res = Object.values(keyEntities)
  68. .filter((item: any) => isEqual(item.valuePath, valuePath))
  69. .map((item: any) => item.key);
  70. return res;
  71. }
  72. export function calcMergeType(autoMergeValue: boolean, leafOnly: boolean): string {
  73. let mergeType: string;
  74. if (leafOnly) {
  75. mergeType = strings.LEAF_ONLY_MERGE_TYPE;
  76. } else if (autoMergeValue) {
  77. mergeType = strings.AUTO_MERGE_VALUE_MERGE_TYPE;
  78. } else {
  79. mergeType = strings.NONE_MERGE_TYPE;
  80. }
  81. return mergeType;
  82. }