Skip to content

Instantly share code, notes, and snippets.

@felipebizz
Created January 15, 2016 21:19
Show Gist options
  • Save felipebizz/6dc7168c1a03b953f81e to your computer and use it in GitHub Desktop.
Save felipebizz/6dc7168c1a03b953f81e to your computer and use it in GitHub Desktop.
Find ancestors and Descendants in a Tree
'use strict';
const findJob = (jobs, id) => {
const found = jobs.filter(job => job.id === id);
return found.length === 0 ? null : found[0];
};
const ancestors = (jobs, id, curr) => {
if (!curr) {
curr = [];
}
const job = findJob(jobs, id);
if (job === null) {
return curr;
}
if (!job.parent) {
return curr;
}
return ancestors(jobs, job.parent, curr.concat([job.parent]));
};
// Verifica se candidateId é ancestral de descendantId
const isAncestor = (jobs, descendantId, candidateId) => (
ancestors(jobs, descendantId).filter(ancestorId => ancestorId === candidateId).length > 0
);
// Verifica se candidateId é descendente de ancestorId
const isDescendant = (jobs, ancestorId, candidateId) => isAncestor(jobs, candidateId, ancestorId);
/*
+-- 11 ----- 111
|
1 --+
|
+-- 12
|
| +--- 14
| |
+-- 13 --+
|
+--- 15
2
*/
const jobs = [ {id: 15, parent: 13}, {id: 14, parent: 13}, {id: 13, parent: 1}, {id: 1, parent: null}, {id: 2, parent: null}, {id:11, parent: 1}, {id: 12, parent: 1}, {id: 111, parent: 11}];
// console.log(ancestors(jobs, 111));
// console.log(isAncestor(jobs, 111, 11));
// console.log(isAncestor(jobs, 111, 12));
// console.log(isDescendant(jobs, 1, 11));
// console.log(isDescendant(jobs, 11, 11));
// console.log(isDescendant(jobs, 1, 111));
// console.log(isDescendant(jobs, 11, 111));
// console.log(isDescendant(jobs, 2, 111));
// const descendants = (jobs, ancestorId) => jobs.map(job => job.id).reduce((result, elem) => {
// if (isDescendant(jobs, ancestorId, elem)) {
// result.push(elem);
// }
// return result;
// }, []);
// Sem o reduce, mas fazendo a mesma coisa
const descendants = (jobs, ancestorId) => {
const result = [];
jobs.map(job => job.id).forEach((elem) => {
if (isDescendant(jobs, ancestorId, elem)) {
result.push(elem);
}
});
return result;
};
console.log(descendants(jobs, 1));
console.log(descendants(jobs, 13));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment