1

Playing with ImmutableJS, documentation needs work and actual working examples.

const a = [["a"],["b"],["c"]]
const b = Immutable.List(a)
const c = Immutable.OrderedSet(a)

b.first()   // => "a"
b.get(1)    // => "b"
c.first()   // => ["a"]
c.get(1)    // => undefined !uh oh!
c.toList().get(1) // => "b" !indirect!

Question: How do I print out the 2nd element of .OrderedSet c without converting it to a .List or loop over the entire list?

Alvin K.
  • 4,329
  • 20
  • 25
  • 1
    Sad story: `{set,orderedSet}.get` accepts a value as an argument and returns the value. https://github.com/facebook/immutable-js/issues/754 – danielepolencic Mar 19 '16 at 11:21
  • @danielepolencic: Agreed that get(0) should be consistent over .Set. Bug report: https://github.com/facebook/immutable-js/issues/810 – Alvin K. Mar 19 '16 at 18:02

1 Answers1

2

You can do it such as:

// using some ES6 features
let ordSet = immutable.OrderedSet([1, 2, 3]) 
let iterator = ordSet[Symbol.iterator] // get iterator to the collection
iterator.next() // 1 
iterator.next() // 2
iterator.next() // 3 

This said, let me note that even if this is not the nicest syntax, from the point of performance, it is the best as it gets: OrderedSet does not provide random access to its elements, each element simply remembers its successor and predecessor. Therefore, getting n-th element requires n hops, whether immutable.js provides some fancy helper for it or not. AFAIK, such linked-list-like implementation of OrderedSet is inevitable, if add / delete should remain fast.

Tomas Kulich
  • 14,388
  • 4
  • 30
  • 35
  • This leads us to the age old issue on [linked list vs array](http://stackoverflow.com/questions/393556/when-to-use-a-linked-list-over-an-array-array-list) vs HashSet vs TreeMap vs HashMap vs [insert your favourite list], each with its own benchmark for `add` / `delete` – Alvin K. Apr 09 '16 at 19:55