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

Function getLowestCommonAncestor

code/communication/public/app.js:2569–2601  ·  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

2567 * different trees.
2568 */
2569function 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.

Callers 1

traverseEnterLeaveFunction · 0.70

Calls 1

getParentFunction · 0.70

Tested by

no test coverage detected