feat: calculate layer

This commit is contained in:
Lin, Hung-Shin committed 2023-11-15 14:30:37 +08:00
1 parent c92a2e1d70
commit fae2d8199d
2 files changed
+80

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
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)
}
}
+50
View File
@@ -0,0 +1,50 @@
import DAG from './dag.js'
describe('dag', () => {
const data = [
{
_id: 'helloworld',
title: 'Hello, Linux World!',
requirements: [],
},
{
_id: 'spell',
title: 'Learn to spell',
requirements: ['helloworld'],
},
{
_id: 'discover',
title: 'Discover the World!',
requirements: ['spell'],
},
{
_id: 'read',
title: 'Read the File',
requirements: ['spell'],
},
{
_id: 'remove',
requirements: ['read', 'discover'],
},
{
_id: 'move',
requirements: ['helloworld'],
},
{
_id: 'copy',
requirements: ['remove', 'move'],
},
]
it('should set layers', () => {
const dag = new DAG(data)
dag.format()
expect(dag.get('helloworld').layer).toBe(1)
expect(dag.get('spell').layer).toBe(2)
expect(dag.get('move').layer).toBe(2)
expect(dag.get('read').layer).toBe(3)
expect(dag.get('discover').layer).toBe(3)
expect(dag.get('remove').layer).toBe(4)
expect(dag.get('copy').layer).toBe(5)
})
})