Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node {
- constructor(i_Val, i_Next = null) {
- this.val = i_Val;
- this.next = i_Next;
- }
- }
- const findPathFromSourceToDestination = (src, dst) => {
- const arr = [];
- // const arr = src.split("/").map((curFolder) => new Node(curFolder));
- const headSrc = src
- .split("/")
- .reduceRight((next, val) => new Node(val, next), null);
- const headDst = dst
- .split("/")
- .reduceRight((next, val) => new Node(val, next), null);
- let travelerSrc = headSrc;
- let travelerDst = headDst;
- while (travelerSrc && travelerDst && travelerSrc.val === travelerDst.val) {
- travelerSrc = travelerSrc.next;
- travelerDst = travelerDst.next;
- }
- // now we are at the point of one after the intersection
- // src = a->b->d->g->null
- // |
- // v
- // dst = c->e->f->null
- // so we need to add to the result path '..' x times
- // when x = nodes left from travelerSrc to null - in our case - 2
- while (travelerSrc) {
- arr.push("..");
- travelerSrc = travelerSrc.next;
- }
- // now we are back to a->b, we need to add all nodes from travelerDst
- while (travelerDst) {
- arr.push(travelerDst.val);
- travelerDst = travelerDst.next;
- }
- return arr.join("/");
- };
- const src = "a/b/d/g";
- const dst = "a/b/c/e/f";
- console.log(findPathFromSourceToDestination(src, dst));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement