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

Function getLowestCommonAncestor

code/composition/public/app.js:2672–2704  ·  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

2670 * different trees.
2671 */
2672function getLowestCommonAncestor(instA, instB) {
2673 var depthA = 0;
2674 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
2675 depthA++;
2676 }
2677 var depthB = 0;
2678 for (var tempB = instB; tempB; tempB = getParent(tempB)) {
2679 depthB++;
2680 }
2681
2682 // If A is deeper, crawl up.
2683 while (depthA - depthB > 0) {
2684 instA = getParent(instA);
2685 depthA--;
2686 }
2687
2688 // If B is deeper, crawl up.
2689 while (depthB - depthA > 0) {
2690 instB = getParent(instB);
2691 depthB--;
2692 }
2693
2694 // Walk in lockstep until we find a match.
2695 var depth = depthA;
2696 while (depth--) {
2697 if (instA === instB || instA === instB.alternate) {
2698 return instA;
2699 }
2700 instA = getParent(instA);
2701 instB = getParent(instB);
2702 }
2703 return null;
2704}
2705
2706/**
2707 * Return if A is an ancestor of B.

Callers 1

traverseEnterLeaveFunction · 0.70

Calls 1

getParentFunction · 0.70

Tested by

no test coverage detected