Advertisement
JoachimBrnd

Untitled

Jan 20th, 2025
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 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]
  32. };
  33. }
  34. }
  35.  
  36. // Build path from bottom up
  37. let pathParts = [];
  38. if (root) pathParts.push(root);
  39.  
  40. // Add current slug
  41. pathParts.push(slug);
  42.  
  43. // Traverse up the parent chain
  44. let currentParentId = parentId;
  45. while (currentParentId) {
  46. const parentRow = rowsById[currentParentId.toString()];
  47. if (!parentRow) break;
  48.  
  49. // Add parent slug to path (after root if exists)
  50. pathParts.splice(root ? 1 : 0, 0, parentRow.slug);
  51.  
  52. // Move to next parent
  53. currentParentId = parentRow.parentId;
  54. }
  55.  
  56. return '/' + pathParts.join('/');
  57.  
  58. } catch (error) {
  59. return "#ERROR!";
  60. }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement