
如何使用缩进优化 javascript 代码以获取路径层级
已给出的代码成功执行,但提出进一步优化的请求。以下经优化的 javascript 代码提供了提升的性能和简洁度。
const lines = str.split("\n")
.map(line => ({
level: ~~((line.length - line.trimStart().length) / 4),
value: line.trim()
}));
lines.reduce((level, it) => {
if (it.level - level > 1) {
it.level = level + 1;
}
return it.level;
}, 0);
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));该代码的优化要点:
- 使用 map() 遍历行并计算缩进级别,无需外部分析。
- 使用 reduce() 修正层级差,防止越级情况。
- 采用循环更新 path,避免同一层的冗余计算。
- 使用 join() 直接生成路径字符串,减少推演。










