Skip to content

Instantly share code, notes, and snippets.

@mrpoptart
Created July 6, 2021 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrpoptart/ec88dca6804f393dd8a708ccd82fb546 to your computer and use it in GitHub Desktop.
Save mrpoptart/ec88dca6804f393dd8a708ccd82fb546 to your computer and use it in GitHub Desktop.
/*
* Who are the { parents, children, grandchildren, grandparents, siblings, ... } of { name }?
*
* Let's start with just a small set:
* Amy and Bob have children Carol, Doug, Erin
* Carol and Xavier have children Mike, Nina
*
* Amy + Bob <- we only care about genetic relations, don't fuss about the "+" as something we need!
* / | \
* Doug Erin Carol + Xavier
* / / \
* Ralphie Mike Nina
*/
class Person{
constructor(name, parents, siblings, children){
this.name = name;
this.parents = parents || [];
this.siblings = siblings || [];
this.children = children || [];
}
addParent(parent){
this.parents.push(parent);
}
addSibling(sibling){
if(this === sibling) {
return;
}
if(this.siblings.indexOf(sibling) === -1) {
this.siblings.push(sibling);
}
for(let s in this.siblings) {
if(this.siblings[s].siblings.indexOf(this) === -1) {
this.siblings[s].addSibling(this);
}
}
}
addChild(child){
this.children.push(child);
child.addParent(this);
for(let c in this.children) {
this.children[c].addSibling(child);
child.addSibling(this.children[c])
}
}
getGrandparents(names=false){
const grandparents = [];
for(let p in this.parents) {
if(this.parents[p].parents) {
grandparents.push(...this.parents[p].parents);
}
}
return grandparents;
}
getGrandchildren(names=false){
const grandchildren = [];
for(let c in this.children) {
if(this.children[c].children) {
grandchildren.push(...this.children[c].children);
}
}
return grandchildren;
}
getCousins(){
const cousins = [];
for(let p in this.parents) {
for(let s in this.parents[p].siblings){
cousins.push(...this.parents[p].siblings[s].children)
}
}
return cousins;
}
}
const Amy = new Person("Amy");
const Bob = new Person("Bob");
const Doug = new Person("Doug");
const Erin = new Person("Erin");
const Carol = new Person("Carol");
const Xavier = new Person("Xavier");
const Mike = new Person("Mike");
const Nina = new Person("Nina");
const Ralphie = new Person("Ralphie");
Amy.addChild(Doug)
Amy.addChild(Erin)
Amy.addChild(Carol)
Bob.addChild(Doug)
Bob.addChild(Erin)
Bob.addChild(Carol)
Carol.addChild(Mike)
Carol.addChild(Nina)
Xavier.addChild(Mike)
Xavier.addChild(Nina)
Doug.addChild(Ralphie)
console.log(Mike.getCousins().map((ar)=>{return ar.name}));
console.log(Nina.getCousins().map((ar)=>{return ar.name}));
console.log(Nina.getGrandparents().map((ar)=>{return ar.name}));
console.log(Ralphie.getCousins().map((ar)=>{return ar.name}));
console.log(Amy.getGrandchildren().map((ar)=>{return ar.name}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment