原始的代码确实难读:手动 for 循环;各种 flag 用于控制循环。这些面向过程式的编程风格极大的增加了阅读难度。
以下是 AI 优化过的代码,利用 js 的函数式编程特性,可以以更易读的方式组织代码:
主要的优化点是,用 filter 和 some 代替冗长的 for 循环。这里面的 Map 确实不是必要的,如果换成 string array 的话看起来会更简单一点。
```Javascript
const originArr = [
 { value: "q", children: [{ value: "w", children: [{ value: "e" }, { value: "r" }] }, { value: "t", children: [{ value: "" }, { value: "y" }, { value: "u" }] }, { value: "i" }] },
 { value: "o" },
];
const targetMap = new Map([
 ["q/w/e", undefined],
 ["q/t", undefined],
]);
function formatArr(arr, path = '') {
 return arr.filter(item => {
 const currentPath = path ? `${path}/${item.value}` : item.value;
 // Check if the current path is needed
 if (targetMap.has(currentPath)) {
 return true;
 }
 // Check if any target path starts with the current path
 const isPrefix = Array.from(targetMap.keys()).some(key => key.startsWith(currentPath));
 if (!isPrefix) {
 return false;
 }
 // Recursively filter children if they exist
 if (item.children) {
 item.children = formatArr(item.children, currentPath);
 }
 return true;
 });
}
const copyArr = formatArr(JSON.parse(JSON.stringify(originArr)));
console.log(originArr, copyArr);
```