Hacker News new | ask | show | jobs
by onsclom 1271 days ago
Great points! I am still trying to figure out how to best use functional programming with JavaScript. I've found writing performance critical parts imperatively while being conscious about shared mutable state is a decent compromise.

> My second advice is to not use recursion to process arrays languages (like JavaScript) that have a very limited call stack size.

Can also confirm this, here was my process on the some of the harder days in Advent of Code:

1. I wonder if I can solve this in a pure functional style with JavaScript

2. Yay, it works on the example input

3. Oh, I hit the call stack limit on the real input

4. Time to rewrite the recursion as a loop lol

4 comments

Shame since ECMAScript 2015 was supposed to give of proper tail calls in JavaScript, but Blink chickened out and so did Gecko.
> I am still trying to figure out how to best use functional programming with JavaScript.

IME avoid recursion, use immutability in the large while avoiding in local scope beyond a simple .map.filter chain, and on the backend I allow myself fp-ts to have sane error handling (I assumed TypeScript there but I'd just not ever use vanilla JS nowadays).

With that said I'd really, really rather use a compile to JS lang that does the optimizations for you, specially for frontend use cases.

> trying to figure out how to best use functional programming with JavaScript

Use ES6 classes to guard every property read and write behind a method-call.

You can avoid mutable state by making methods return only primitive data, including JSON. Then nobody can modify such state from the outside. You control and can easily observe all state-changes.

5. refactor loop as loop function