我有一个如下对象:
var myMap = {
v1: ['v2', 'v4', 'v5'],
v2: ['x', 'v4', 'y'],
v3: ['v2', 'v4', 'v5'],
v4: ['e', 'v1', 'v5'],
v5: ['v2', 'v4', 'v3'],
};
我必须找到循环的实体图,而不必将其转换为图。
输出类似于:
var myDep = {
v1: {isCyclic: true, cyclicDependents: ['v4']},
v2: {isCyclic: false, cyclicDependents: []},
v3: {isCyclic: true, cyclicDependents: ['v5']},
v4: {isCyclic: true, cyclicDependents: ['v1', 'v5']},
v5: {isCyclic: true, cyclicDependents: ['v4', 'v3']},
};
我尝试了以下操作:
var graph = {
v1: ["v2", "v4", "v5"],
v2: ["x", "v4", "y"],
v3: ["v2", "v4", "v5"],
v4: ["e", "v1", "v5"],
v5: ["v2", "v4", "v3"]
};
var myDep = {
v1: { isCyclic: false, cyclicDependents: [] },
v2: { isCyclic: false, cyclicDependents: [] },
v3: { isCyclic: false, cyclicDependents: [] },
v4: { isCyclic: false, cyclicDependents: [] },
v5: { isCyclic: false, cyclicDependents: [] }
};
myDep = Object.keys(graph).reduce((a, b) => {
graph[b] &&
graph[b].forEach(d => {
if (graph[d] && ~graph[d].indexOf(b)) {
a[b].isCyclic = true;
a[b].cyclicDependents.push(d);
}
});
return a;
}, myDep);
console.log(myDep);
是否还有其他方法可以使其表现更好。我认为使用try catch块以迭代方式使用JSON.stringify也是一种方法。但我不确定性能会提高/降低。
答案 0 :(得分:4)
您可以使用一种功能来检查循环性质并存储访问的节点以防止永远循环。
结果是一个带有开始键及其循环节点的对象。所需的格式留给读者练习。
function isCyclic(node, target, [...visited] = []) {
if (node === target) return true;
if (visited.includes(node) || !myMap[node]) return false;
visited.push(node);
return myMap[node].some(n => isCyclic(n, target, visited));
}
var myMap = { v1: ['v2', 'v4', 'v5'], v2: ['x', 'v4', 'y'], v3: ['v2', 'v4', 'v5'], v4: ['e', 'v1', 'v5'], v5: ['v2', 'v4', 'v3'] },
result = {};
Object.entries(myMap).forEach(([k, v]) => result[k] = v.filter(n => isCyclic(n, k)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }