class AncestralTree { constructor(name, ancestorNode) { this.name = name; this.ancestor = ancestorNode; } } const a = new AncestralTree("A", null); const b = new AncestralTree("B", a); const d = new AncestralTree("D", b); const e = new AncestralTree("E", b); const c = new AncestralTree("c", a); const f = new AncestralTree("F", c); const g = new AncestralTree("G", c); const h = new AncestralTree("H", d); const i = new AncestralTree("I", d); function ancestorFunc(topAnc, desc1, desc2) { const list1 = ancList(desc1); const list2 = ancList(desc2); //list1 = [A, B, D] //list2 = [A, B] for (let i = 0; i < list1.length; i++) { if (list1[i] !== list2[i]) { return list1[i - 1].name } } } function ancList (myNode) { let node = myNode let ancestors = []; while (node){ ancestors.unshift(node) node = node.ancestor } return ancestors; } console.log(ancestorFunc(a, h, i))
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter