* Return the lowest common ancestor of A and B, or null if they are in * different trees.
(instA, instB)
| 1765 | * different trees. |
| 1766 | */ |
| 1767 | function getLowestCommonAncestor(instA, instB) { |
| 1768 | var depthA = 0; |
| 1769 | for (var tempA = instA; tempA; tempA = getParent(tempA)) { |
| 1770 | depthA++; |
| 1771 | } |
| 1772 | var depthB = 0; |
| 1773 | for (var tempB = instB; tempB; tempB = getParent(tempB)) { |
| 1774 | depthB++; |
| 1775 | } |
| 1776 | |
| 1777 | // If A is deeper, crawl up. |
| 1778 | while (depthA - depthB > 0) { |
| 1779 | instA = getParent(instA); |
| 1780 | depthA--; |
| 1781 | } |
| 1782 | |
| 1783 | // If B is deeper, crawl up. |
| 1784 | while (depthB - depthA > 0) { |
| 1785 | instB = getParent(instB); |
| 1786 | depthB--; |
| 1787 | } |
| 1788 | |
| 1789 | // Walk in lockstep until we find a match. |
| 1790 | var depth = depthA; |
| 1791 | while (depth--) { |
| 1792 | if (instA === instB || instA === instB.alternate) { |
| 1793 | return instA; |
| 1794 | } |
| 1795 | instA = getParent(instA); |
| 1796 | instB = getParent(instB); |
| 1797 | } |
| 1798 | return null; |
| 1799 | } |
| 1800 | |
| 1801 | /** |
| 1802 | * Return if A is an ancestor of B. |
no test coverage detected