utils.js 891 B

123456789101112131415161718192021222324252627282930
  1. export const findNodeLevel = (nodes, targetKey, curLevel = 0) => {
  2. for (let node of nodes) {
  3. if (node.id === targetKey) {
  4. return curLevel;
  5. }
  6. if (node.children) {
  7. const childLevel = findNodeLevel(node.children, targetKey, curLevel + 1);
  8. if (childLevel !== -1) {
  9. return childLevel;
  10. }
  11. }
  12. }
  13. return -1;
  14. };
  15. export const findKeyPath = (nodes, targetKey, path = []) => {
  16. for (let i = 0; i < nodes.length; i++) {
  17. const node = nodes[i];
  18. const currentPath = [...path, i];
  19. if (node.id === targetKey) {
  20. return currentPath;
  21. }
  22. if (node.children) {
  23. const childPath = findKeyPath(node.children, targetKey, currentPath);
  24. if (childPath) {
  25. return childPath;
  26. }
  27. }
  28. }
  29. return null;
  30. };