Advertisement
JoachimBrnd

Untitled

Jan 20th, 2025
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. function BUILDPATH(id, slug, parentId, root) {
  2. if (!id || !slug) return "";
  3.  
  4. try {
  5. const sheet = SpreadsheetApp.getActiveSheet();
  6. const range = SpreadsheetApp.getActiveRange();
  7. const formula = range.getFormula();
  8.  
  9. const matches = formula.match(/([A-Z]+)\d+/g);
  10. if (!matches) return "/" + (root ? root + "/" : "") + slug;
  11.  
  12. const [idCol, slugCol, parentCol] = matches.map(match => match.replace(/\d+/, ''));
  13.  
  14. // Get the full data once
  15. const lastRow = sheet.getLastRow();
  16. const data = sheet.getRange(1, 1, lastRow, sheet.getLastColumn()).getValues();
  17.  
  18. // Get column indexes
  19. const idColIndex = sheet.getRange(idCol + "1").getColumn() - 1;
  20. const slugColIndex = sheet.getRange(slugCol + "1").getColumn() - 1;
  21. const parentColIndex = sheet.getRange(parentCol + "1").getColumn() - 1;
  22.  
  23. // Create a map of all rows by ID for faster lookup
  24. const rowsById = {};
  25. for (let i = 0; i < data.length; i++) {
  26. const rowId = data[i][idColIndex];
  27. if (rowId) {
  28. rowsById[rowId.toString()] = {
  29. id: rowId,
  30. slug: data[i][slugColIndex],
  31. parentId: data[i][parentColIndex] ? data[i][parentColIndex].toString() : null
  32. };
  33. }
  34. }
  35.  
  36. // Build path parts array
  37. let pathParts = [];
  38.  
  39. // Start with the current item's slug
  40. pathParts.push(slug);
  41.  
  42. // Traverse up the parent chain
  43. let currentParentId = parentId ? parentId.toString() : null;
  44. let maxIterations = 20; // Prevent infinite loops
  45.  
  46. while (currentParentId && maxIterations > 0) {
  47. const parentRow = rowsById[currentParentId];
  48. if (!parentRow) break;
  49.  
  50. pathParts.unshift(parentRow.slug);
  51. currentParentId = parentRow.parentId;
  52. maxIterations--;
  53. }
  54.  
  55. // Add root at the beginning if provided
  56. if (root) pathParts.unshift(root);
  57.  
  58. return '/' + pathParts.join('/');
  59.  
  60. } catch (error) {
  61. return "#ERROR! " + error.toString();
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement