working: update file-graph-algorithm

This commit is contained in:
Chen, Tai-Lin committed 2023-08-25 20:05:28 +08:00
1 parent ab570e9c1b
commit 821896f292
5 files changed
+162 -36

No files matched your search

+39 -16
View File
@@ -1,35 +1,54 @@
import FileNode from './fileNode.js'
import { FileNotExistsError } from './errors.js'
export default class FileGraph {
constructor(root) {
this.root = new FileNode(root)
}
add(file) {
add(files) {
// Logic to add the file node to the graph
// You can implement the logic to find the appropriate location in the file graph
// If the file node already exists, throw an error
const newNode = new FileNode(file)
this.root.addChild(newNode, { makeParents: true })
files.forEach((file) => {
this.root.addChild(file, { makeParents: true })
})
}
remove(file) {
remove(files) {
// Logic to remove a file node from the graph
// If the file node is a folder, also remove all children
// If the file node doesn't exist, throw an error
const nodeToRemove = this.findNode(file)
if (nodeToRemove) {
const parentNode = this.findParentNode(file)
if (parentNode) {
parentNode.children = parentNode.children.filter(
(child) => child !== nodeToRemove
files.forEach((file) => {
const pathFolders = file.path
.split('/')
.filter((folder) => folder.length > 0)
const fileName = pathFolders.pop()
let currentNode = this.root
for (const folder of pathFolders) {
currentNode = currentNode.children.find(
(child) => child.name === folder
)
if (!currentNode) {
throw new FileNotExistsError(
`File not found: ${fileToFind.path}, ${this.toString()}`
)
}
}
if (!currentNode.children.some((child) => child.name === fileName)) {
throw new FileNotExistsError(
`File not found: ${file.path}, ${this.toString()}`
)
} else {
currentNode.children = currentNode.children.filter(
(child) => child.name !== fileName
)
}
} else {
throw new Error(`File node not found: ${file.path}`)
}
})
}
discover(eventFiles) {
@@ -37,13 +56,17 @@ export default class FileGraph {
// Overwrite the file graph with the provided files
// Remove file nodes that don't exist anymore and add new ones
const updatedNodes = eventFiles.map((file) => new FileNode(file))
this.root = new FileNode({
const newRoot = new FileNode({
path: '/',
type: 'folder',
discovered: true,
children: updatedNodes,
})
eventFiles.forEach((file) => {
newRoot.addChild(file, { makeParents: true })
})
this.root = newRoot
}
handleEvent(event) {