gpt4 book ai didi

javascript - 无序列表 "merging"通过递归函数问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:37:11 25 4
gpt4 key购买 nike

我有以下问题:

我有这个字符串,看起来像这样:

* item1
* item2
** item21
** item22
* item3
** item31
** item32
***item321
* item4

这类似于无序列表,(这意味着 item21 和 item22 是 item 2 的子类别,等等)。

我想用 javascript/node.js 代码编写,输出就是这样

array = [
"item1",
"item2 item21",
"item2 item22",
"item3 item31",
"item3 item32 item321",
"item4"
];

如您在输出中所见,显示文本的项目按类别和子类别合并。

我的想法是以某种方式使用递归函数。之前,我使用换行符将文本拆分为数组。但是,不知何故,我坚持实现了该功能。

对于任何想法或伪代码/代码,我将很高兴和感激。再次感谢大家。

最佳答案

这里有一个片段可以帮助您入门。

请注意,您的示例输入存在轻微的不一致,因此我冒昧地假设这是一个拼写错误。具体来说,您输入的倒数第二行 ***item321* 之后缺少一个空格。我认为这是一个打字错误,但如果不是,请随意从我的正则表达式中删除空格。

let input = `
* item1
* item2
** item21
** item22
* item3
** item31
** item32
*** item321
* item4
`;

let lines = input
.split('\n')
.filter(a => a)
.map(line => {
let [_, stars, value] = line.match(/^(\**) (.*)/);
return {depth: stars.length, value};
});

let hierarchy = [];
let output = [];
lines.forEach((line) => {
if (hierarchy.length && line.depth <= hierarchy[hierarchy.length - 1].depth)
output.push(hierarchy.map(a => a.value).join(' '));

while (hierarchy.length && line.depth <= hierarchy[hierarchy.length - 1].depth)
hierarchy.pop();

hierarchy.push(line);
});
output.push(hierarchy.map(a => a.value).join(' '));

console.log(output);

关于javascript - 无序列表 "merging"通过递归函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55905285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com