Skip to content

Commit

Permalink
Merge pull request #1 from biothings/range-error
Browse files Browse the repository at this point in the history
fix RangeError, add entity cap
  • Loading branch information
tokebe authored Aug 11, 2023
2 parents 524df56 + d747c73 commit 37ebdbe
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 15 deletions.
7 changes: 6 additions & 1 deletion __test__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,10 @@ test('multiple', () => {
test('no descendants', () => {
let curies = ['DOID:0060527'];
let descendants = getDescendants(curies);
expect(descendants).not.toHaveProperty('DOID:0060527');
expect(descendants['DOID:0060527'].length).toBe(0);
});

test('recursive', () => {
let curies = ['UMLS:C0012634'];
let descendants = getDescendants(curies);
});
31 changes: 17 additions & 14 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const _ = require('lodash');
let data = {};
let loaded = false;

const ENTITY_CAP = 100;

//load data from json files based on ontologies
const loadData = () => {
if (loaded) return;
Expand All @@ -22,22 +24,23 @@ const loadData = () => {
exports.getDescendants = (curies, recursive = true) => {
loadData();
if (recursive) {
//recursively get all children
const children = _.pick(data, curies);
let visited = []; // keep track of visited nodes to prevent infinite recursion
const getDescendantsRecur = (curies, prop) => {
for (let curie of curies) {
if (data[curie] && !visited.includes(curie)) {
visited.push(curie);
children[prop].push(...data[curie]);
getDescendantsRecur(data[curie], prop);
//run level order traversal to get closest descendants
const children = {};

for (let curie of curies) {
children[curie] = [];
level = [curie];
while (level.length > 0 && children[curie].length < ENTITY_CAP) {
next_level = [];
for (let c of level) {
if (data[c]) {
children[curie].push(...data[c]);
next_level.push(...data[c]);
}
}
level = next_level;
}
}
//get children recursively for each key value of children
for (const prop in children) {
getDescendantsRecur(children[prop], prop);
children[prop] = _.uniq(children[prop]);
children[curie] = _.uniq(children[curie]).slice(0, ENTITY_CAP);
}
return children;
} else
Expand Down

0 comments on commit 37ebdbe

Please sign in to comment.