refactored: links between notes (avoid recursion)

This commit is contained in:
quenousimporte 2023-02-04 16:13:55 +01:00
parent e1d9227b54
commit cba4848da0
1 changed files with 44 additions and 32 deletions

76
main.js
View File

@ -573,64 +573,76 @@ function selectvault()
function ancestors(note) function ancestors(note)
{ {
var list = [... new Set(parents(note))]; var list = [note];
list.forEach(title => var result = [];
while (list.length)
{ {
var parent = localdata.find(n => n.title == title); var current = list.shift();
if (parent && !list.find(p => p.title == parent)) if (result.indexOf(current) == -1)
{ {
list = list.concat(ancestors(parent)); result.push(current);
list = list.concat(parents(current));
} }
}) }
return list; return result;
} }
function descendants(note) function descendants(note)
{ {
var list = [... new Set(children(note))]; var list = [note];
list.forEach(title => var result = [];
while (list.length)
{ {
var child = localdata.find(n => n.title == title); var current = list.shift();
if (child && !list.find(p => p.title == child)) if (result.indexOf(current) == -1)
{ {
list = list.concat(descendants(localdata.find(n => n.title == title))); result.push(current);
} list = list.concat(children(current));
}) }
return list; }
return result;
} }
function children(note) function children(note)
{ {
return (note.content return (note.content
.match(/\[\[([^\]]*)\]\]/g) || []) .match(/\[\[([^\]]*)\]\]/g) || [])
.map(l => l.replace("[[", "").replace("]]", "")); .map(l => l.replace("[[", "").replace("]]", ""))
.map(l => getnote(l));
} }
function parents(note) function parents(note)
{ {
return localdata return localdata
.filter(n => n.content.indexOf("[[" + note.title + "]]") != -1) .filter(n => n.content.indexOf("[[" + note.title + "]]") != -1);
.map(n => n.title); }
function connected(note)
{
var list = [note];
var result = [];
while (list.length)
{
var current = list.shift();
if (result.indexOf(current) == -1)
{
result.push(current);
list = list.concat(children(current)).concat(parents(current));
}
}
return result;
} }
function shownotelinks() function shownotelinks()
{ {
try searchinlist(connected(currentnote).map(n => n.title))
{ .then(loadnote);
var list = ancestors(currentnote).reverse();
var index = list.length;
list.push(currentnote.title);
list = list.concat(descendants(currentnote));
searchinlist(list, null, index)
.then(loadnote);
}
catch(err)
{
showtemporaryinfo("Loop detected");
}
} }
function showoutline() function showoutline()
{ {
var outline = {}; var outline = {};