Search code examples
data-structuresfunctional-programmingjavascriptpersistent-data

Javascript functional library with persistent data structures


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.


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