673 B33 lines
Blame
1export interface TreeData {
2 parentById: Record<string, string>;
3 childrenById: Record<string, string[]>;
4}
5
6export const findCommonAncestor = (id1: string, id2: string, { parentById }: TreeData) => {
7 const visited = new Set();
8 let currentId = id1;
9
10 // Edge case with self edges
11 if (id1 === id2) {
12 return parentById[id1] || 'root';
13 }
14
15 while (currentId) {
16 visited.add(currentId);
17 if (currentId === id2) {
18 return currentId;
19 }
20 currentId = parentById[currentId];
21 }
22
23 currentId = id2;
24 while (currentId) {
25 if (visited.has(currentId)) {
26 return currentId;
27 }
28 currentId = parentById[currentId];
29 }
30
31 return 'root';
32};
33