Files
linux-odyssey/packages/utils/dag.js
T
2023-11-15 14:30:37 +08:00

31 lines
650 B
JavaScript

export default class DAG {
constructor(nodes) {
this.nodes = new Map(nodes.map((node) => [node._id, node]))
this.edges = []
}
setLayer(id) {
console.log(`setLayer(${id})`)
const node = this.nodes.get(id)
if (!node) {
throw new Error(`Node ${id} not found`)
}
if (node.layer !== undefined) {
return node.layer
}
const previousLayer = node.requirements.map((rId) => this.setLayer(rId))
node.layer = Math.max(...previousLayer, 0) + 1
return node.layer
}
format() {
this.nodes.forEach((_, id) => {
this.setLayer(id)
})
}
get(id) {
return this.nodes.get(id)
}
}