fix: find node

This commit is contained in:
EnixCoda 2019-03-10 14:51:46 +08:00
parent e46df20de6
commit 62086e9d15
No known key found for this signature in database
GPG key ID: 0C1A07377913A1DD

View file

@ -48,17 +48,36 @@ export function friendlyFormatShortcut(shortcut?: string) {
}
}
/**
* if item's name matches path, return self-depth of the item
* else return 0
*/
function measureDistance(item: TreeNode, path: TreeNode['name'][]): number {
const pathString = path.join('/')
if (item.name.indexOf(pathString + '/') === 0) {
// If accessing a leading item of compressed node, path will be shorter than item.name
return path.length
} else if (pathString === item.name || pathString.indexOf(item.name + '/') === 0) {
return item.name.split('/').length
}
return 0
}
/**
* look for the first item matches given path under root.content
*/
export function findNode(
root: TreeNode,
path: string[],
path: TreeNode['name'][],
callback?: (node: TreeNode) => void,
): TreeNode | undefined {
if (Array.isArray(root.contents)) {
for (const content of root.contents) {
if (content.name === path[0]) {
if (callback) callback(content)
if (path.length === 1) return content
return findNode(content, path.slice(1), callback)
for (const item of root.contents) {
const distance = measureDistance(item, path)
if (distance > 0) {
if (callback) callback(item)
if (path.length === distance) return item
return findNode(item, path.slice(distance), callback)
}
}
}