Advertisement
yarin0600

Untitled

Dec 1st, 2023
753
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Node {
  2.   constructor(i_Val, i_Next = null) {
  3.     this.val = i_Val;
  4.     this.next = i_Next;
  5.   }
  6. }
  7.  
  8. const findPathFromSourceToDestination = (src, dst) => {
  9.   const arr = [];
  10.   //   const arr = src.split("/").map((curFolder) => new Node(curFolder));
  11.   const headSrc = src
  12.     .split("/")
  13.     .reduceRight((next, val) => new Node(val, next), null);
  14.  
  15.   const headDst = dst
  16.     .split("/")
  17.     .reduceRight((next, val) => new Node(val, next), null);
  18.  
  19.   let travelerSrc = headSrc;
  20.   let travelerDst = headDst;
  21.  
  22.   while (travelerSrc && travelerDst && travelerSrc.val === travelerDst.val) {
  23.     travelerSrc = travelerSrc.next;
  24.     travelerDst = travelerDst.next;
  25.   }
  26.  
  27.   // now we are at the point of one after the intersection
  28.   // src = a->b->d->g->null
  29.   //          |
  30.   //          v
  31.   //    dst = c->e->f->null
  32.   // so we need to add to the result path '..' x times
  33.   // when x = nodes left from travelerSrc to null - in our case - 2
  34.   while (travelerSrc) {
  35.     arr.push("..");
  36.     travelerSrc = travelerSrc.next;
  37.   }
  38.  
  39.   // now we are back to a->b, we need to add all nodes from travelerDst
  40.   while (travelerDst) {
  41.     arr.push(travelerDst.val);
  42.     travelerDst = travelerDst.next;
  43.   }
  44.  
  45.   return arr.join("/");
  46. };
  47.  
  48. const src = "a/b/d/g";
  49. const dst = "a/b/c/e/f";
  50.  
  51. console.log(findPathFromSourceToDestination(src, dst));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement