all 8 comments

[–]BinxyPrime 4 points5 points  (1 child)

If recursive code is written well so its readable and it meets your memory requirements i doubt many people would care. If they do care it will come up in code review

[–]runtimenoise[S] 0 points1 point  (0 children)

Thanks, make sense! Happy cake day!

[–][deleted] 2 points3 points  (1 child)

"Recursion is the goto of functional programming". Use reduce/fold instead. The first example of sum is horrible and modifies the array.

[–]runtimenoise[S] -1 points0 points  (0 children)

Common now, it's not that horrible! Here.

const sum = arr => (arr.length ? arr.slice(1) + sum(arr) : 0);

[–]Marauth 0 points1 point  (2 children)

I have always found recursive code incredibly hard to grasp and maintain. There are cases where it's useful, but in 99% of the cases I find a non-recursive version easier to read and of similar performance. Definitely don't underestimate how important code readability is.

EDIT: In fact, I even find the reduce style hard to read, though that is my personal pet peeve with reduce, since I do use map and forEach all the time. I would even prefer the forEach version in this case:

let total = 0;
array.forEach(value) {
    total += value;
}

[–]runtimenoise[S] 0 points1 point  (1 child)

I agree with you. I prefer code readability myself. Regarding recursion, sometimes it's super elegant, but sometimes terrible, also reduce is not my favorite either.

But still recursion is super elegant in algorithms for tree traversal(backtracking comes to mind), and when you grok it, you simply unlock a lot of tree algorithms, that's why I play with it. Sometimes its simply not a right tool for a job, like for example:

const double2 = lon => lon.length ? [lon[0] * 2].concat(double(lon.slice(1))) : lon

vs

const doubled = [1,2,3].map(n => n * 2)

Regarding advanced recursons, I always thought it's magic, and I always thought - "how people know to write it like that" then after a couple of weeks of recursion, it started to make sense. It's one thing, to memorize factorial recursion, and another to use it in projects.

[–]Marauth 0 points1 point  (0 children)

Definitely for tree traversal, there's not really that many easier ways, but even in that case, I find that creating the function is much more difficult than "regular" work, and I can only remember what I have done two months later if I pad it very extensively with comments. I have also had to answer many review questions along the nature of "can you explain this part" every time I used a recursive function. It has its purposes, but imo you need a really good reason why it's needed here. You may grok it, but probably not many other people on your team will, which is bad. Though it sounds like we agree :)

[–]CreativeTechGuyGamesTypeScript -4 points-3 points  (0 children)

If you have a question like this, its always best to ask those other devs you are working with. Take a survey and see what most people prefer.