refactor
This commit is contained in:
parent
0a6148c73f
commit
e8f1d1db1e
60 changed files with 2417 additions and 612 deletions
49
js/family_graph.js
Normal file
49
js/family_graph.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"use strict";
|
||||
|
||||
(function (global) {
|
||||
function buildGraph(nodes = [], opts = {}) {
|
||||
const idOf = opts.idOf || (n => n?.id);
|
||||
const edgesOf = opts.edgesOf || ((n) => [...(n?.parents || []), ...(n?.children || [])]);
|
||||
const byId = new Map(nodes.filter(Boolean).map(n => [idOf(n), n]).filter(([id]) => id));
|
||||
const graph = new Map([...byId.keys()].map(id => [id, new Set()]));
|
||||
const connect = (a, b) => {
|
||||
if (!a || !b || a === b || !graph.has(a) || !graph.has(b)) return;
|
||||
graph.get(a).add(b);
|
||||
graph.get(b).add(a);
|
||||
};
|
||||
for (const node of byId.values()) {
|
||||
const id = idOf(node);
|
||||
for (const next of edgesOf(node, byId)) connect(id, next);
|
||||
}
|
||||
return { graph, byId };
|
||||
}
|
||||
|
||||
function connectedComponents(nodes = [], opts = {}) {
|
||||
const { graph, byId } = buildGraph(nodes, opts);
|
||||
const sort = opts.sort || null;
|
||||
const nodeList = [...byId.values()].sort(sort || (() => 0));
|
||||
const seen = new Set();
|
||||
const comps = [];
|
||||
for (const node of nodeList) {
|
||||
const start = opts.idOf ? opts.idOf(node) : node.id;
|
||||
if (!start || seen.has(start)) continue;
|
||||
const stack = [start];
|
||||
const comp = [];
|
||||
seen.add(start);
|
||||
while (stack.length) {
|
||||
const id = stack.pop();
|
||||
const item = byId.get(id);
|
||||
if (item) comp.push(item);
|
||||
for (const next of graph.get(id) || []) {
|
||||
if (seen.has(next)) continue;
|
||||
seen.add(next);
|
||||
stack.push(next);
|
||||
}
|
||||
}
|
||||
if (!opts.filter || opts.filter(comp)) comps.push(sort ? comp.sort(sort) : comp);
|
||||
}
|
||||
return comps;
|
||||
}
|
||||
|
||||
global.TarinaiFamilyGraph = { buildGraph, connectedComponents };
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
Loading…
Add table
Add a link
Reference in a new issue