丽红~
丽红~Lv1
晚上撸完算法题,顺手翻了下npm install的源码(就是node_modules/npm/lib/install.js那块),发现它居然是用拓扑排序来处理包依赖的!之前一直以为只是简单递归…结果真去看才发现,每个包的install顺序得按依赖图的入度来排,不然像a依赖b、b又依赖a这种循环引用就直接跪了 刚试了下手动写了个简化版:
function topologicalSort(graph) {
  const inDegree = {};
  for (let node in graph) inDegree = 0;
  for (let node in graph) 
    for (let dep of graph) 
      inDegree = (inDegree || 0) + 1;
  const queue = Object.keys(inDegree).filter(n => inDegree === 0);
  const result = [];
  while (queue.length) {
    const cur = queue.shift();
    result.push(cur);
    for (let dep of graph || []) {
      inDegree--;
      if (inDegree === 0) queue.push(dep);
    }
  }
  return result.length === Object.keys(graph).length ? result : [];
}
运动完脑子清醒点,突然就通了…npm这活儿真不简单啊!