Skip to content

Instantly share code, notes, and snippets.

@coleea
Created August 29, 2024 16:49
Show Gist options
  • Save coleea/548d3f25b86bbd50658da6f90e17ce97 to your computer and use it in GitHub Desktop.
Save coleea/548d3f25b86bbd50658da6f90e17ce97 to your computer and use it in GitHub Desktop.
class FamilyTree {
constructor() {
this.relationships = {};
}
addParent = (parent, child) => {
this.relationships[parent] = this.relationships[parent] || new Set();
this.relationships[parent].add(child);
}
isParent = (parent, child) =>
this.relationships[parent]?.has(child) || false;
grandparent = (grandparent, grandchild) =>
Object.entries(this.relationships).some(([parent, children]) =>
children.has(grandchild) && this.isParent(grandparent, parent));
sibling = (person1, person2) =>
Object.values(this.relationships).some(children =>
children.has(person1) && children.has(person2) && person1 !== person2);
cousin = (person1, person2) =>
Object.entries(this.relationships).some(([parent1, children1]) =>
children1.has(person1) &&
Object.entries(this.relationships).some(([parent2, children2]) =>
children2.has(person2) && this.sibling(parent1, parent2)));
ancestor = (ancestor, descendant) => {
if (this.isParent(ancestor, descendant)) return true;
return Array.from(this.relationships[ancestor] || [])
.some(child => this.ancestor(child, descendant));
}
familyMembers = (person) => {
let members = new Set([person]);
Object.entries(this.relationships).forEach(([parent, children]) => {
if (this.ancestor(parent, person) || parent === person) {
members.add(parent);
children.forEach(child => members.add(child));
}
});
return Array.from(members);
}
}
// 사용 예
const family = new FamilyTree();
['john', 'susan'].forEach(parent => ['mary', 'mike'].forEach(child => family.addParent(parent, child)));
family.addParent('mary', 'ann');
family.addParent('mary', 'tom');
family.addParent('mike', 'emma');
console.log(family.grandparent('john', 'ann')); // true
console.log(family.sibling('mary', 'mike')); // true
console.log(family.cousin('ann', 'emma')); // true
console.log(family.ancestor('john', 'emma')); // true
console.log(family.familyMembers('john')); // ['john', 'mary', 'mike', 'ann', 'tom', 'emma']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment