Getting Y.Map size

Thanks to this project, I’ve been introduced to the Map in javascript and have checked out the docs on Y.Map, and wondered if it was intentional that there wasn’t a .size made available for checking how many keys are being stored? Seems like plenty of other Map methods have been implemented. Found this discussion about a potential toMap() function… and while one could iterate through the keys and count, wondered if I’m missing something obvious or a 1-liner for checking the length/size?

A little more research, and figured out a potential 1-liner: Array.from(ymap).length

Hmm… good point. Would be happy to receive a PR for this!

1 Like

Was just digging into the source and found the following size function exists.
Made a PR removing that get which hopefully makes it public… my workflow isn’t setup at the moment for building/testing, but hopefully it just works…

On a side note, it seems that ES6 now allows JS Maps to use a wide range of types for the key… is there a specific reason that Y.Map needs to use a string for the key? I’m using integers for other Maps within my code and when comparing to the Y.Map instance, convert them ie. ymap.has(session.toString()) – it’s not a big deal, but curious if/where it could be modifed (AbstractType.js)? Or for the CRDT syncing etc it’s not worth it? (true i’m probably now treating a Y.Map a bit like the Y.Array – but found it to be much smoother for syncing has/get/set/delete than rebuilding the array each change).

Oh. It seems ymap.size is already implemented. It’s a computed property. So just do ymap.size instead of ymap.size() (which will result in an error).

Yes, ES6 Maps allow more key-values (also objects and symbols). However, this adds quite some overhead on the implementation and is generally not what users are looking for. In most cases it can be simulated by converting the number to a string. This is what Redis is doing for example.

The protocol is extensible enough to allow us to enable, for example, numbers as keys. However, it’s unlikely that we will because we should keep the implementation small.

:man_facepalming: – awesome and I’ll cancel my current PR. Instead I’ll move it to the docs repo and suggest listing it in the API before forEach(), since it’s so useful (for me) to know how many iterations will take place in some cases (or in my case, using the count as the ID for adding more sessions).

Re: keys, yeah, just sticking to strings makes sense and good to know that toString() is a decent approach.

1 Like