如何优化以下js代码,通过缩进来获取路径的层级?
a
b
c
k
d
e
f
h
g
let str = `a
b
c
k
d
e
f
h
g`
const space_count = (str) => {
return str.indexOf(str.trim())
}
const submit = () => {
let p = str.trim().split("\n")
// 父路径的每一项的名称
let parentPathSplit = []
// 合并后的路径列表
let joinPath = []
// 缩进的次数,4个空格为一个缩进
let indentationCount = 0
let trimPath = ""
for (let item of p) {
trimPath = item.trim()
if (trimPath == "") {
continue
}
indentationCount = Math.ceil(space_count(item) / 4)
// 如果缩进的次数为0,说明顶层路径,重置parentPathSplit
if (indentationCount == 0) {
parentPathSplit = [trimPath]
joinPath.push(parentPathSplit.join("/"))
continue
}
// 缩进的次数与parentPathSplit对应,0是顶层,1是第二层...
// 次数与长度相同,添加
// 如果下一次还是相同的缩进,说明是并列关系,此时,长度 > 次数
if (indentationCount == parentPathSplit.length) {
parentPathSplit[indentationCount] = trimPath
joinPath.push(parentPathSplit.join("/"))
continue
}
// 如果父级是1个缩进,当前为3个缩进,多了一个,以下代码修正这种问题
if (indentationCount > parentPathSplit.length) {
indentationCount = parentPathSplit.length
parentPathSplit[indentationCount] = trimPath
}
// 合并父目录及当前路径
joinPath.push(parentPathSplit.slice(0, indentationCount).join("/") + "/" + trimPath)
}
console.log(joinPath)
}
输出:
[
"a",
"a/b",
"a/b/c",
"a/b/k",
"a/d",
"e",
"e/f",
"e/f/h",
"e/g"
]
代码能走通,结果也正常,问题是优化,可能还有未顾及到的地方。谢谢
回复
1个回答
test
2024-06-18
let str = `a
b
c
k
d
e
f
h
g`;
const lines = str.split("\n")
.map(line => ({
// 通过空格数计算层级
level: ~~((line.length - line.trimStart().length) / 4),
value: line.trim()
}));
// e 和 f 之间的层级差出现了越级的情况,修正 level,方便后面的 path 算法
lines.reduce((level, it) => {
if (it.level - level > 1) {
it.level = level + 1;
}
return it.level;
}, 0);
// 这部分算法不想解释了,自己跟吧
// 主要目的就是用 path 保存处理过程,循环事更新对应层次,
// 并截取(段)组合成路径字符串
const path = [];
const result = [];
for (const it of lines) {
const { level, value } = it;
path[level] = value;
result.push(path.slice(0, level + 1).join("/"));
}
console.log(JSON.stringify(result, null, 4));
结果
[
"a",
"a/b",
"a/b/c",
"a/b/k",
"a/d",
"e",
"e/f",
"e/f/h",
"e/g"
]
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容