DEV Community


Discussion on: What happened to Immutable.JS? And how can we react?

iquardt profile image
Iven Marquardt

This comment got way too long, sorry.

I'm using persistent data strucutres in node and gain both performance benefits and purity. However, I'd say you don't necessarily need immutable.js:

Single Linked Lists

Single linked lists have the form of a pair tuple [head, tail]. While they are little familiar in Javascript they are inherently persistent and thus have several benefits:

  • unshift/shift for free
  • list concatenation as efficient as with mutable arrays

Here is an example:

list append

Objects as Trees with Sharing

If you use objects as trees you can merely update the path to a node while the rest of the tree structure is shared. This is a very efficient copy mechanism. You can find an implementation in my lib:

Hash Array Mapped Tries

If you really need persistent (ordered) maps/sets or arrays you can implement a HAMT yourself. There is a basic implementation in my lib. It is really not that hard.

alekseiberezkin profile image
Aleksei Berezkin Author

Thanks for sharing links. While linked lists definitely have their usage, we must keep in mind that access by index costs O(n)O(n) for them. Yet, because each item produces additional object(s), memory fragmentation increases.

Ordered map is indeed a problem in JS, and devs should either implement it, or use some lib, or just order and array of [key, value] tuples. Which is best? It depends 🙂

iquardt profile image
Iven Marquardt

You're right. However, I think index based access is overrated, because you don't need it that often.

Btw. I don't think immer.js is a good solution, because it doesn't seem to compose.