MCPcopy Create free account
hub / github.com/krasimir/react-in-patterns / getLowestCommonAncestor

Function getLowestCommonAncestor

code/new-context-api/public/app.js:1895–1927  ·  view source on GitHub ↗

* Return the lowest common ancestor of A and B, or null if they are in * different trees.

(instA, instB)

Source from the content-addressed store, hash-verified

1893 * different trees.
1894 */
1895function getLowestCommonAncestor(instA, instB) {
1896 var depthA = 0;
1897 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
1898 depthA++;
1899 }
1900 var depthB = 0;
1901 for (var tempB = instB; tempB; tempB = getParent(tempB)) {
1902 depthB++;
1903 }
1904
1905 // If A is deeper, crawl up.
1906 while (depthA - depthB > 0) {
1907 instA = getParent(instA);
1908 depthA--;
1909 }
1910
1911 // If B is deeper, crawl up.
1912 while (depthB - depthA > 0) {
1913 instB = getParent(instB);
1914 depthB--;
1915 }
1916
1917 // Walk in lockstep until we find a match.
1918 var depth = depthA;
1919 while (depth--) {
1920 if (instA === instB || instA === instB.alternate) {
1921 return instA;
1922 }
1923 instA = getParent(instA);
1924 instB = getParent(instB);
1925 }
1926 return null;
1927}
1928
1929/**
1930 * Return if A is an ancestor of B.

Callers 1

traverseEnterLeaveFunction · 0.70

Calls 1

getParentFunction · 0.70

Tested by

no test coverage detected