Question

I'm looking for a functional library with persistent data structures. I only need nested arrays and dictionaries. There are some functional javascript libraries, but they are not geared towards immutability. I want to be able to write

var dict = makeDictionary({
  'foo': 1;
  'bar': {
     'ely': 2;
  }
});
var newDict = dict.assoc('foo', 42).assoc('bar', 'tender', 30).dissoc('bar', 'ely');
assert.eq dict.bar.ely, 2; // unchanged
assert.eq newDict.bar.tender, 30; // added
assert.eq newDict.bar.ely, undefined; // removed

While underscore comes close in some cases, especially with arrays, it modifies dictionary arguments. I could also use clojurescript, but I'd prefer a more light-weight approach.

Was it helpful?

Solution

I finalized my implementation of Persistent Map (and will finish Persistent Vector soon) for JavaScript, because there seems to be an increasing demand.

There are several specifics compared to e.g. Java (lack of equals, hashCode to rely on), so the implementation uses sorted balanced binary tree (balancing is actually simplified and sped up by immutability) and === for equality and < or custom function for lower-than.

the code of Feat.js (the project code name) is available at feat-sorted-map.js at github.com

You can see a page with working tests in action online at feat.js at cofylang.org

Currently, there is no documentation except the source code and tests, but I am working on finishing that as well.

Update: there is an implementation of a persistent vector available there as well, and the speed has been improved in orders of magnitude. (it has been cleaned-up as well) feat-vector.js at github.com

OTHER TIPS

I'd take a look at Mori. It packages up ClojureScript's functional data structure for use from plain old Javascript. Since the data structures are coming from ClojureScript I'd expect them to be better tested, more complete and more performant than other libraries.

https://github.com/swannodette/mori

There's also:

https://github.com/hughfdjackson/immutable

Which is based on the persistent hash trie algorithm here:

https://github.com/hughfdjackson/persistent-hash-trie

Might be worth looking into.

The code for this is nicer imho, but my benchmarks show it's running nearly an order of magnitude slower than the one listed above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top