util.ts 2.2 KB

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