Map Recursively an Infinite Tree Data Structure Easily with JS and React

preview_player
Показать описание
Credits to Alex Merced for giving an easy algorithm for mapping recursively an array with javascript.

Repository code:
Рекомендации по теме
Комментарии
Автор

Wow, i spent 4 day to find out how to map recursively a obj tree. Thank you for the explaination !

Ben-zmcb
Автор

Excellent description. Just what I have been looking for. Thanks to you and Alex.

markcaple
Автор

js doesn't have tail call optimization, so it should hit a max callstack error on data with deep levels, ~10-20k levels
I think it might be worth normalizing the data, keeping structure of nodes separate from their content

no_name_qwe
Автор

One question since I have been using this. How would you change it elegantly to return an output type TOutput that didn't necessarily have a children property. For instance the "children" property in the new type becomes "questions"

So

type TreeKeyMenuInput = {
id: number
prompt: string
children?: TreeKeyMenuInput[]
}

type TreeKeyMenuOutput = {
id: number
weighting: number
questions?: TreeKeyMenuOutput[]
}

const keyMenu: TreeKeyMenuInput[] = [
{
id: 1,
prompt: "What is your name?",
children: [
{ id: 2, prompt: "What is your age?" },
{
id: 3,
prompt: "What is your shoe size?",
children: [
{ id: 4, prompt: "Do you think your feet are big?" },
{ id: 5, prompt: "Do you think your feet are small?" },
],
},
],
},
]

Becomes

[
{
id: 1,
weighting: 100,
questions: [
{ id: 2, weighting: 70 },
{
id: 3,
weighting: 50,
questions: [
{ id: 4, weighting: 20 },
{ id: 5, weighting: 10 },
],
},
],
},
]

markcaple
Автор

not only your very bad, but event you forgot to mention some key titles so i dont have to watch this video

sinacorleon
visit shbcf.ru