11 ms·
Immutable Data Collections for Javascript
- falava 12y agoThere is also Mori[1], a JavaScript API for using ClojureScript's persistent data structures: [1] http://swannodette.github.io/mori/
- swah 12y agoI really appreciate when a new project mentions the ones in the same space - or the ones that inspired it - and why they aren't good enough and a new project was started. The guys in the ATP podcast talked about a similar gesture in the Overcast app, and that most users really enjoyed: https://dl.dropboxusercontent.com/u/19746944/overcast_others.png https://dl.dropboxusercontent.com/u/19746944/overcast_others...
- smrtinsert 12y agoMori also provides clojure like functionality for the new collections greatly simplifying how you would use them - if you don't use Clojure you might think of the additional functions as an underscore for immutable collections. I don't see a reason to use any other immutable js lib when Mori exists.
- misuba 12y agoMori's a bit impractical for use in the browser due to its size.
- taude 12y agoI'm not seeing how a 32 KB download is impractical in browser use do to size (assuming the above statement about 32KB is true). Is there something else to it?
- misuba 12y agoI didn't see any such statement above. From 176K to 37K (that's what I got on my console anyway) is impressive.
- moomin 12y agoIf you use ClojureScript, it strips out unused functions...
- klibertp 12y agoThat would be true for any properly annotated JS fed to Google Closure Compiler, right? I definitely need to learn more about it, as dead code elimination for JavaScript seems very, very hard due to its dynamic nature and I'm curious how they do it. Does anyone know about other JS compilers which try to perform dead code elimination?
- rakoo 12y agoClickable link: https://swannodette.github.io/mori/ https://swannodette.github.io/mori/
- pelle 12y agoMori with it's underscore like API indeed seems much simpler and less C++ and Java like. I guess it depends on your taste.
- vineet 12y agoSounds like more of the pieces of React/Flux are being opensourced. :-) Interesting to see references to TypeScript. Is it prevalent at FB?
- wukkuan 12y agoThis isn't used internally by Facebook at this point. The author mentioned this after your post. https://news.ycombinator.com/item?id=8108741 https://news.ycombinator.com/item?id=8108741
- spyder 12y agoIf you want "pieces" with similar functions to what React has then there is the very modular Mercury too: https://github.com/Raynos/mercury https://github.com/Raynos/mercury
- jannes 12y agoI wish the README would tell us a little bit more about how to use it in conjunction with React. Especially the logic for shouldComponentUpdate() would be interesting.
- EdwardMSmith 12y agoFrom my understanding, it makes shouldComponentUpdate() very simple: return nextProps.value !== this.props.value; If the object is different, it has changed.
- Touche 12y agoI'm not familiar with React, but why would that not be the case without this lib? {} !=== {} EDIT: Maybe I understand. You're saying a parent component might do something like: foo.bar = 'blah'; and then doing a simple equality check foo === foo is not enough, you have to check that the properties have not changed either. Is that correct?
- EdwardMSmith 12y agoExactly. If you have deeply nested data, multiple properties that may change, or arrays, then it becomes quite difficult (and/or slow) to test if there's a difference.
- jannes 12y agoYes, that's how for I've got, too. But then you have a problem if your React component has multiple attributes. Suddenly your check beckomes much larger: return (nextProps.attr1 !== this.props.attr1 || nextProps.attr2 !== this.props.attr2 || nextProps.attr3 !== this.props.attr3 || nextProps.attr4 !== this.props.attr4); Which would result in a lot of boilerplate code if you had to do this for every single attribute in every component in your application. It would be much simpler to just do this check: return nextProps !== this.props; But that's impossible if you're using JSX, because the JSX compiler automatically inserts a normal JavaScript object into your code, instead of an immutable object from this library. So from my point of view this immutable-js library and JSX seem incompatible, which is kind of weird since Facebook apparently uses JSX internally for their React code.
- abaco 12y agoBit confused (ignorant actually) here. Can someone give a 'real world' example of the benefits of immutabile objects in js?
- ionforce 12y agoImmutable objects in general or immutable objects in JavaScript specifically?
- abaco 12y agoA general example would be good :)
- ionforce 12y agoIt is a guarantee to you that the data structure has not been tampered with by the time it reaches you. // pseudo code var fruitBasket = new FruitBasket('banana, 'apple) muckWithFruits(fruitBasket) suspiciousLogger(fruitBasket) weirdCallback(fruitBasket) // here assert(fruitBasket.length == 2) By the time we reach "here", we know that none of the functions since the inception of fruit basket have tampered with it. This may not be a big deal if you are disciplined about never modifying your source data, but this moves the guarantee from a soft one to a mechanical one. And then there's all this typical stuff about functional programming blah blah... But that's the most practical example I can think of.
- bsimpson 12y agoIf everything is immutable, it also makes it a lot easier to parallelize tasks, because you can easily deduce a dependency graph.
- frankosaurus 12y agoIn multi-threaded environments, immutable objects are thread-safe. When multiple threads are sharing data, you would normally have to worry about synchronization. However, immutable data structures guarantee that the shared data will not change, so synchronization issues simply go away. That said, I'm not sure how this applies to JS, which is single-threaded.
- colinramsay 12y agoReact's documentation also discuss their immutability helpers [1]. This new library looks like a better way of implementing this though. Will the documentation be amended to discuss use of immutable-js? [1] http://facebook.github.io/react/docs/update.html http://facebook.github.io/react/docs/update.html
- vjeux 12y agoReact immutability helpers pros: - Work on regular JavaScript Object and Array so it's easy to get started and integrate to your app - You don't need to wrap objects inside of Immutable to use it and you can use `obj.key` and `arr[0]` syntax for accessing them instead of `obj.get('key')` and `arr.get(0)` cons: - There are no safe-guards if you mutate the objects and it'll likely break your app in subtle ways. This kind of discipline is very hard to get in big projects - You are stuck with primitive data structures (instead of map hash trie), so it's not going to be as performant and memory efficient.
- nawitus 12y agoHmm, it seems to be written in TypeScript, but the source is only provided in JavaScript.
- deleted 12y ago[deleted]
- leebyron 12y agoI actually started by writing it in TS and later moved to just a TS declaration file and a raw JS source. This means it can be used smoothly in both environments (similar to using a definitelytyped resource).
- epignosisx 12y agoWhat made you go back to plain javascript?
- gregwebs 12y agoFor an ambitious project this is probably still a better approach. But did you try using the --declaration switch?
- leebyron 12y agoHey, I'm the author of this library. It's definitely inspired by mori (and clojure and Haskell) and the reason I ended up building something different was to present a more JavaScript friendly API (and academically, to learn about HAMT). I've built this over the last couple weeks, and we are not using it internally yet - but I wanted to ensure development of it happened in public.
- dahjelle 12y agoThanks—this looks pretty exciting! I've been using Mori, but this appears to have a more JS-ish API. Can you give some other comparisons to Mori (i.e. feature set, performance, etc.)?
- leebyron 12y agoThe feature set is comparable sans yet to come SortedSet and SortedMap (aka Red Black Tree). Performance should also be comparable if not slightly faster than mori in some iteration cases, as it's tuned for JS instead of ClojureScript and I've forgone some of the functional purity for speed. But this is anecdotal and I don't have any perf tests yet.
- moomin 12y agoI think you might be surprised exactly what running code through an optimising compiler achieves.
- taeric 12y agoI'm curious at what you are hinting at here. Especially when you are discussing the data structure, I've not seen too much magic that an optimizing compiler can really achieve. That is, the compilers are usually more geared to help speed up the code, not so much the data. Any good links showing otherwise?
- swannodette 12y agoFirst off it's very exciting and cool to see a company like Facebook release an open source persistent data structure library for JavaScript. Mori just has more stuff and the benefit of 3 years of development and production use. This becomes quite apparent on the metrics you asked about: - mori is a 32K gzipped browser dependency, tons of helpers functions - immutable-js is a 10K gzipped browser dependency (with Uglify and aggressive mangling), mostly just data structures ClojureScript (and thus Mori) has been continuously tuned for 3 different major JS engines - JavaScriptCore, V8, and SpiderMonkey. Running some basic benchmarks overall Mori comes out ahead on most operations. But there's nothing surprising here, immutable-js is brand spanking new :). Also there are micro-optimizations (which add up) in ClojureScript that are impossible to expose to JS users w/o a compiler. In anycase this is great stuff and I'm excited to see how JavaScript and more specifically React devs leverage these to explore the ideas currently be played around with in ClojureScript/Om/Elm/etc.
- 33a 12y agoAlso relevant (and not included in this collection) is the following functional red-black tree implementation: https://github.com/mikolalysenko/functional-red-black-tree https://github.com/mikolalysenko/functional-red-black-tree
- dreamdu5t 12y agoThe original npm package "immutable" was https://github.com/hughfdjackson/immutable https://github.com/hughfdjackson/immutable (npm install immutable@1.4) Did Facebook buy the npm name from hughfdjackson, did he give it to them, or did NPM switch ownership?
- augustl 12y agoThere's an acknowledgement in the README. https://github.com/facebook/immutable-js/blob/fdc4005fe302866626ab94e060bc06b8381a94be/README.md https://github.com/facebook/immutable-js/blob/fdc4005fe30286...
- Kiro 12y agoI don't understand this whole immutable thing... Why not just avoid changing the data once created? Why do you need a library?
- afandian 12y agoBecause a data structure is useless if you can't change it. You do want to 'change' the data. Immutable structures let you take a data structure and 'modify' it, getting another structure. Anything with a pointer to the first one has a guarantee that it won't ever change. With C-style language structures immutable structures wouldn't be much use. With Clojure, for example, immutability is one of a few mutually complementary features of the language in which it makes perfect sense. Immutability doesn't just mean 'doesn't change'.
- _halgari 12y agoNot good enough. When the time comes that you do need to add something, then what? Clone it? In languages that allow you to freeze a collection, adding something to a frozen collection is often a O(n) operation. Most of the collections in this library provide operations that grow collections in (almost) constant time.
- Kiro 12y ago> Clone it? Yes, isn't that enough?
- dannysatan 12y agoNo, it's time and memory inefficient. When you add something to immutable data structure, a new structure is created but internally it shares the data with a structure it was derived from.
- afandian 12y agoLet's say you want to create a set by recursing along a million long sequence, collecting the unique values. This would be done with an operation called `reduce`. The time and storage complexity of that would be exponential if each step you had to clone a copy of the output list. With a persistent data structure, as much of the structure as possible is re-used. And a list is the simplest possible structure. What about a tree? Using `reduce` is, I would say, in the top 5 techniques used in functional programming. And it would be severely hobbled without efficient persistent immutable structures.
- derengel 12y agoSo you can use the Clojurescript/Om/Reagent/React model without Clojurescript, nice for people who don't want or can't jump into Clojurescript right now.
- ScottBurson 12y agoIf anyone is interested in functional collections for Common Lisp or Java, have a look at FSet: http://www.ergy.com/FSet.html http://www.ergy.com/FSet.html
- Strilanc 12y agoI have to admit, I find it odd that we name immutable data structures based on what they don't do instead of what they do. Of course, what they do is efficient persistence. You want a snapshot of the data? You want a non-volatile reference? You've already got one! That's the feature. They should be called persistent data structures.
- the_af 12y agoI'm sure you are aware in many cases they are indeed called persistent data structures: http://en.wikipedia.org/wiki/Persistent_data_structure http://en.wikipedia.org/wiki/Persistent_data_structure
- TheLoneWolfling 12y agoYou can have an efficiently persistent data structure that isn't immutable. For example, a rope that reorganizes internal nodes to maximize structure sharing.
- leebyron 12y agoThat is true! In fact, an earlier version of this library was called "persistent-js", and I know this is a pretty subtle distinction - I found it easier to talk to people about when I talked about it via immutability and so I ended up naming the library that way.
- collyw 12y agoCan someone give me a good example of where immutable data structures are better than mutable ones. I know that you are more likely to mess up and have side effects with mutable data structures, but so far all I have heard is theory.
- TheLoneWolfling 12y agoWell, for one thing you don't need to make defensive copies all over the place. Look at OBJ05-J and OBJ06-J, for example. Some of these copies can be removed via optimization, but not always.
- couchand 12y agoThe big win is they enable lazy evaluation: you can defer the evaluation of an expression until it's needed, or discard the result and compute it again later, or cache the result of an expression and not need to re-evaluate, a flexibility which can be useful in many situations. You also get undo/redo stacks basically for free, since you simply maintain references to the previous n immutable states. As Om demonstrates, they also make possible significant optimizations of code that takes various view of the same underlying data, like rendering routines.
- boubiyeah 12y agoWhat's the use of immutable data collections if you have to constantly revert to mutable arrays to render anything? Any gain from the persistent collection is lost in wasteful Array creating (Poor gc)