I'm not sure this is true, especially for tree-like structures. For example: find the first file named "treasure.js" in directory "projects" and all it's subdirectories.
After my first contact with a computer in the 1980's, I taught myself to program in BASIC and Z80 assembler. I went on to study Computer Science and have enjoyed a long career in Software Engineering.
I agree with Pawel, there are problems loops cannot solve and where recursion is a more efficient strategy. In your example Adam, you only make one recursive call from the function but there are also use case where a function might call itself more than once per cycle. The graphical flood fill algorithm is a good example.
Not sure about all cases, but you can definitely do your example without the need for a stack, but using a loop to create an array of folders to search etc. I just did a similar thing creating a tree that needed an final unrolled array rather than a recursive structure.
Yeah, probably no need for the directories array to be mutable though, you'd just replace it on each iteration with all of the next level down directories.
Mechanic by trade, software dev because it's fun as heck. And, well, it will be nice to WFH when I decide my body has had enough. No commute, A/C, less silica glistening in the early morning air!
I'm not sure this is true, especially for tree-like structures. For example: find the first file named "treasure.js" in directory "projects" and all it's subdirectories.
It is definitely wrong.
But recursion can always be implemented by a stack.
Because functions are implemented by stacks.
I agree with Pawel, there are problems loops cannot solve and where recursion is a more efficient strategy. In your example Adam, you only make one recursive call from the function but there are also use case where a function might call itself more than once per cycle. The graphical flood fill algorithm is a good example.
Not sure about all cases, but you can definitely do your example without the need for a stack, but using a loop to create an array of folders to search etc. I just did a similar thing creating a tree that needed an final unrolled array rather than a recursive structure.
So like with a
while
andcurrent_directory
variable anddirectories
mutable array?Yeah, probably no need for the directories array to be mutable though, you'd just replace it on each iteration with all of the next level down directories.
The quick and dirty trick I use:
i
to track your working position in the arraypush
any "to be processed later" items onto the arrayi
on each iterationi >= array.length
JSFiddle
Explanation
Just for the sake of semantics, but arrays in JS are mutable by design!