Last active
March 25, 2024 18:46
-
-
Save gerwitz/fa96343b29be2c752a866037198539e8 to your computer and use it in GitHub Desktop.
recursion example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
{ | |
"toplist": [ | |
{ | |
"name": "something", | |
"color": "black", | |
"lines": [ | |
{ | |
"name": "first", | |
"color": "blue" | |
}, | |
{ | |
"name": "second", | |
"color": "red", | |
"lines": [ | |
{ | |
"name": "first_again", | |
"color": "blueish" | |
}, | |
{ | |
"name": "second_again", | |
"color": "orange", | |
"lines": [ | |
{ | |
"name": "first_once_more", | |
"color": "chartreuse" | |
}, | |
{ | |
"name": "second_once_more", | |
"color": "magenta" | |
} | |
] | |
} | |
] | |
}, | |
{ | |
"name": "third", | |
"color": "green" | |
} | |
] | |
} | |
] | |
} | |
--- | |
var lines = 👆.toplist; | |
var count = 1; | |
var depth = 0; | |
function print_lines(lines, count, depth) { | |
for (const line of lines) { | |
console.log( | |
count, ', ', | |
depth, ' deep: ', | |
line.name, ' - ', line.color | |
); | |
if (line.lines) { | |
// recurse! | |
print_lines(line.lines, count, depth); | |
} | |
} | |
} | |
--- | |
1, 0 deep: something - black | |
2, 1 deep: first - blue | |
3, 1 deep: second - red | |
4, 2 deep: first_again - blueish | |
5, 2 deep: second_again - orange | |
6, 1 deep: third - green | |
--- | |
// what if we want to stop halfway and restart there later? | |
var skip_until = 'first_again'; | |
var engaged = false; | |
function print_lines(lines, count, depth, skip_until, engaged) { | |
for (const line of lines) { | |
if (line.name == skip_until) { | |
engaged = true; // from now on, do the thing | |
} | |
if (engaged) { | |
console.log( | |
count, ', ', | |
depth, ' deep: ', | |
line.name, ' - ', line.color | |
); | |
} | |
if (line.lines) { | |
print_lines(line.lines, count, depth, skip_until, engaged); | |
} | |
} | |
} | |
--- | |
4, 2 deep: first_again - blueish | |
5, 2 deep: second_again - orange | |
6, 1 deep: third - green |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment