问题
typescript 如何 把 类型为 type ElCascaderOptionsType = {
label: string;
value: string;
children?: ElCascaderOptionsType[]
} 的数组铺平的 一维字符串数组,children 之间用 ' / ' 分隔
大瓦特版本
TypeScript
type ElCascaderOptionsType = {
label: string;
value: string;
children?: ElCascaderOptionsType[]
}
createZdStringArray(options: ElCascaderOptionsType[]): string[] {
const result: string[] = [];
const traverse = (node: ElCascaderOptionsType, currentPath: string[]) => {
const newPath = [...currentPath, node.label];
if (!node.children || !node.children.length) {
result.push(newPath.join(' / '));
return;
}
node.children.forEach(child => {
traverse(child, newPath);
});
};
options.forEach(option => {
traverse(option, []);
});
return result;
}
deepseek 版本
TypeScript
type ElCascaderOptionsType = {
label: string;
value: string;
children?: ElCascaderOptionsType[]
}
function flattenLeafPaths(
options: ElCascaderOptionsType[],
parentPath: string = ''
): string[] {
let result: string[] = [];
for (const option of options) {
const currentPath = parentPath
? `${parentPath} / ${option.label}`
: option.label;
if (!option.children || option.children.length === 0) {
// 叶子节点
result.push(currentPath);
} else {
// 非叶子节点,继续递归
const childPaths = flattenLeafPaths(option.children, currentPath);
result = result.concat(childPaths);
}
}
return result;
}
deepseek 给出大瓦特的优化版本
TypeScript
type ElCascaderOptionsType = {
label: string;
value: string;
children?: ElCascaderOptionsType[]
}
function flattenLeafPaths(
options: ElCascaderOptionsType[],
parentPath: string[] = []
): string[] {
const result: string[] = [];
for (const option of options) {
const currentPath = [...parentPath, option.label];
if (!option.children || option.children.length === 0) {
result.push(currentPath.join(' / '));
} else {
result.push(...flattenLeafPaths(option.children, currentPath));
}
}
return result;
}
豆包给出大瓦特的优化版本
TypeScript
// 定义类型(方便理解,实际项目中已有 ElCascaderOptionsType)
type ElCascaderOptionsType = {
label: string;
value?: string | number;
children?: ElCascaderOptionsType[];
};
function createZdStringArray(options: ElCascaderOptionsType[]): string[] {
// 空输入直接返回空数组,避免无效遍历
if (!Array.isArray(options) || options.length === 0) {
return [];
}
const result: string[] = [];
// 递归遍历函数,职责单一:处理单个节点的路径
const traverse = (node: ElCascaderOptionsType, currentPath: string[]) => {
// 过滤空 label,避免路径出现 " / / " 等异常
const validLabel = node.label?.trim() || '';
if (!validLabel) return;
// 浅拷贝路径数组,避免修改父级路径(核心:保持路径的独立性)
const newPath = [...currentPath, validLabel];
// 叶子节点:拼接路径并加入结果
if (!node.children || !node.children.length) {
result.push(newPath.join(' / '));
return;
}
// 非叶子节点:递归遍历子节点
node.children.forEach(child => traverse(child, newPath));
};
// 遍历根节点,初始化路径为空数组
options.forEach(option => traverse(option, []));
return result;
}