在一些业务中,我们需要处理依赖关系,比如循环依赖。下面的代码实现了循环依赖的检测,检测到存在循环依赖时,终止检测流程,并且打印依赖链。缺点是没有检测出所有的循环依赖,后续加以改进:
<script>
function checkDpes(list) {
const depMap = {};
const findNode = function (key) {
return list.find(it => it.key === key)
}
const findDeps = function (key, deps, path) {
deps.forEach(it => {
if (key === it) {
throw new Error("circle dep for " + [key, ...path, it].join(' => '))
}
if (depMap[key].indexOf(it) === -1) {
depMap[key].push(it)
const node = findNode(it)
if (node.deps && node.deps.length) {
findDeps(key, node.deps, [...path, it])
}
}
})
}
list.forEach(it => {
depMap[it.key] = []
findDeps(it.key, it.deps || [], [])
});
return depMap;
}
// 测试用例
var list = [
{
key: 'A',
deps: ['B', 'C', 'D']
},
{
key: 'B',
deps: ['C']
},
{
key: 'C',
deps: ['D']
},
{
key: 'D',
deps: ['B']
},
{
key: 'E',
}
]
var res = checkDpes(list)
console.log(res)
</script>