* Return the lowest common ancestor of A and B, or null if they are in * different trees.
(instA, instB)
| 2567 | * different trees. |
| 2568 | */ |
| 2569 | function getLowestCommonAncestor(instA, instB) { |
| 2570 | var depthA = 0; |
| 2571 | for (var tempA = instA; tempA; tempA = getParent(tempA)) { |
| 2572 | depthA++; |
| 2573 | } |
| 2574 | var depthB = 0; |
| 2575 | for (var tempB = instB; tempB; tempB = getParent(tempB)) { |
| 2576 | depthB++; |
| 2577 | } |
| 2578 | |
| 2579 | // If A is deeper, crawl up. |
| 2580 | while (depthA - depthB > 0) { |
| 2581 | instA = getParent(instA); |
| 2582 | depthA--; |
| 2583 | } |
| 2584 | |
| 2585 | // If B is deeper, crawl up. |
| 2586 | while (depthB - depthA > 0) { |
| 2587 | instB = getParent(instB); |
| 2588 | depthB--; |
| 2589 | } |
| 2590 | |
| 2591 | // Walk in lockstep until we find a match. |
| 2592 | var depth = depthA; |
| 2593 | while (depth--) { |
| 2594 | if (instA === instB || instA === instB.alternate) { |
| 2595 | return instA; |
| 2596 | } |
| 2597 | instA = getParent(instA); |
| 2598 | instB = getParent(instB); |
| 2599 | } |
| 2600 | return null; |
| 2601 | } |
| 2602 | |
| 2603 | /** |
| 2604 | * Return if A is an ancestor of B. |
no test coverage detected