我需要对由名称和依赖项列表(由名称组成)组成的对象数组进行排序。
这个数组的一个例子是:
[
{ name: 'a', requires: ['b', 'c'] },
{ name: 'b', requires: ['c'] },
{ name: 'c', requires: [] },
]
我希望这个数组能够被排序,使得需要特定依赖项的项目会在其所需的依赖项之后。
实际上,该数组可能包含更多项目,如果存在循环依赖关系,则排序函数抛出错误也可以。
示例输出:
[
{ name: 'c', requires: [] }, // first, no dependencies, and required by both the others
{ name: 'b', requires: ['c'] }, // second, because it needs `c` first
{ name: 'a', requires: ['b', 'c'] }, // last, because requires both the others
]
什么是最简洁的方法实现它?
Array.sort
,但它并不适合这项工作。 - Fez Vrasta