DEV Community

Discussion on: When you think your functional code is stack safe

Collapse
 
functional_js profile image
Functional Javascript

Interesting analysis Iven.

Is there any reason you wouldn't just do this?...

const pipe = (...fns) => v => fns.reduce((r, fn) => fn(r), v);

const inc = x => x + 1;
const aFns = Array(1e5).fill(inc); //arr of funcs

console.log(pipe(...aFns)(0)); //100000
Enter fullscreen mode Exit fullscreen mode
Collapse
 
iquardt profile image
Iven Marquardt • Edited

No, you missed the whole point of the post! In order to keep your code pure while working with data bases, local storage, file systems, random numbers, dates etc. you need to defer the impure computations. You do that by merely describing them. This may lead to stack overflows as I demonstrated with the contrived example above.

Collapse
 
functional_js profile image
Functional Javascript

You've lost me there.

Could you give me an example of where my code above would throw a RangeError (stack overflow)?

Thread Thread
 
iquardt profile image
Iven Marquardt • Edited

No offence, but I can't help ya. I wasn't talkin about your exmaple, because it doesn't make any sense in the context of my post. You built a variadic applicator, which is dual to function composition. You cannot compare function application f => x => f(x) with composition f => g => x => f(g(x)). Both have completely different operational semantics.

Thread Thread
 
functional_js profile image
Functional Javascript

Sounds pretty deep in the academics. ;)

When building applications I test if the behavior is robust and if it's performant and achieves the desired result.

Good luck.