feat: add merge function

Able to deal with:
1.  merge a subtree
This commit is contained in:
wancat authored and Chen, Tai-Lin committed 2023-08-28 14:39:52 +08:00
1 parent 1778780364
commit a66de4dfe1
5 files changed
+114 -5

No files matched your search

+43 -3
View File
@@ -11,11 +11,15 @@ export default class FileNode extends File {
addChild(fileInput, { makeParents } = {}) {
const file = new FileNode(fileInput)
if (file.path === this.path) {
throw new DuplicateItemError('File already exists in the tree')
throw new DuplicateItemError(
`File ${file.path} already exists in the tree: ${this.toString()}`
)
}
if (this.children.some((child) => child.path === file.path)) {
throw new DuplicateItemError('File already exists in the tree')
throw new DuplicateItemError(
`File ${file.path} already exists in the tree: ${this.toString()}`
)
}
const parentPath = dirname(file.path)
@@ -37,11 +41,47 @@ export default class FileNode extends File {
})
this.addChild(parent, { makeParents })
} else {
throw new ParentNotExistsError('Parent path not found in the tree')
throw new ParentNotExistsError(
`Parent path not found in the tree, ${file.path}, ${this.path}`
)
}
}
}
merge(fileNode) {
// Merge the children of the provided file node into this node
// If a child already exists, merge the children of that child
// If a child does not exist, add it to this node
if (fileNode.path === this.path) {
fileNode.children.forEach((child) => {
const existingChild = this.children.find((c) => c.path === child.path)
if (existingChild) {
existingChild.merge(child)
} else {
this.children.push(child)
}
})
// If a child exists in this node but not in the provided node, remove it
this.children = this.children.filter((child) =>
fileNode.children.some((c) => c.path === child.path)
)
} else if (this.contains(fileNode)) {
const childNode = this.children.find((child) => child.contains(fileNode))
if (childNode) {
childNode.merge(fileNode)
} else {
this.addChild(fileNode)
}
} else {
throw new Error(
'Cannot merge file nodes with different paths',
this.path,
fileNode.path
)
}
}
toString() {
const indent = ' '.repeat(this.path.split('/').length - 1)
const suffix = this.isDirectory() ? '/' : ''