Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Facebook's Immutable also provides Cursors for its immutable collections: https://github.com/facebook/immutable-js#cursors


I found immutable-js's cursors to be rather limited for use with react. Using them is very verbose, and you often end up nesting 2 or 3 little anonymous functions when doing mutations.

I ended up hacking my own version of the same idea, but with an explicit reference to a mutable data slot, much like the cursors in this post do.

I use a lot of Immutable.Record for domain objects, and I found that I could get nicely succinct code by adding a getter property to the cursor for each field in a record. It yields a new cursor if the value is an immutable collection too, or else the actual value the cursor points to. This seems like a weird heuristic until you realize that most programming languages make the same distinction (primitive values are cloned, object references are not).

This allows me to write code like

    <span>{this.props.user.group.name}</span>
Where this.props.user is a cursor, not an immutable collection. This is cool, because I only pass around subcursors around my component tree, but I can address them as if they're the values themselves when rendering. And I can still mutate them as a cursor.

I didn't publish this code, or even evaluate the performance of it, but if anyone cares I don't mind sharing.


(Author here) I explored an API like that, the problem I ran into was that often you don't want to refine all the way to a primitive; e.g. What is the value of the whole record so I can validate it? Sometimes you want the record, sometimes you want the cursor.


I noticed that you probably always want the value if the value is a leaf of the tree (typically a primitive value). Similarly, for validation, do you validate records of the values on the records? If the syntax to access the values via a record cursor or via a record is exactly the same, then you can just pass the cursor to the validation function, rather than the record. The validation function doesn't even need to know that it got a cursor.

I'm curious whether you could shoot any holes in that reasoning.


I'd be interested... I'm setting up a new react project and just diving into which immutable data piece to use. Seems there's no real consensus at this point which is tricky, I'd love to see more examples.


I believe that's exactly what I was planning to do for my next project based on React. I'm very interested in your implementation.


Can someone give real world examples when this would be better? It seems to be copy-on-write in a way.


Assuming you are referring to immutability in general, this post does a great job of showing the benefits.

http://swannodette.github.io/2013/12/17/the-future-of-javasc...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: