swannodette / mori

ClojureScript's persistent data structures and supporting API from the comfort of vanilla JavaScript

Home Page:http://swannodette.github.io/mori

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Essential vector methods missing?

tszekely-spotcap opened this issue · comments

Hello, I've started using mori on an experimental project a few weeks ago and all was good until I wanted to do some updates on a vector.

1 . The first thing I tried to do was to update an object from the vector, based on its ID
Since there is no update method for vectors, I'd naturally do something like:

  • find the element's index
  • update/replace the element at index

...but there is no "findIndex" method. the closest thing to a real find method is "some", but it doesn't give you the index, just the value.

I ended up doing:

files: mori.map(
        file => (
          file.getId() === fileInfo.id ?
            file.setInfo(fileInfo) :
            file
        ),
        state.files
      )

but this seems kind of inefficient.

2 . Add some elements to the vector, replacing the existing ones with the same ID (but maybe different values in other properties)

This was very tedious, and I ended up converting the vector to array, doing the operations and then converting the resulting array back to vector. Again, inefficient.

I tried using a set, but both elements with same ID ended up in the result and there's no way of defining the equality check predicate.

Am I missing something here or mori's missing some pretty important things?

You do that with the updateIn function.

this is the function signature
mori.updateIn(coll, keys, function)

and this is the example from the documentation
var h = mori.hashMap("foo", mori.vector(1, 2, 3)); mori.updateIn(h, ["foo", 1], mori.inc); // => {"foo" [1 3 3]}

the second parameter is an array of the keys, you can use this for nested collections as well as for simple collections.