[Gambas-user] Rename a Collection Key retaining the order
Tobias Boege
tobs at taboege.de
Sun Jan 9 23:03:03 CET 2022
On Sun, 09 Jan 2022, Bruce Steers wrote:
> Is there a simple way to rename a collection key name but retain the order?
>
> I found i can rename it using Swap but it pops the item at the and of the
> collection index.
>
> Best i have so far is this fuction that copies and returns the collection
> with a preserved order.
> so if my second collection item had the key "t2" I can do this...
>
Your copy solution is the only one I can come up with. While looking at
the wiki and source code, I noticed that the Collection.Key property
used in the For Next loop is a read/write property, but I found no use
of that fact...
As you are undoubtedly aware, the hash table datatype that Collection
implements in Gambas is usually an unsorted "pile of data" that has some
internal structure facilitating the lookup of data by a string. The fact
that Gambas guarantees that keys are maintained in insertion order and
that iteration always uses this order is a small bonus, but this is more
of an addon than a really exposed feature. You're experiencing this right
now because while it's technically possible to do this efficiently in the
current implementation, there is no API to rename a key without changing
its place in the key order.
If changing keys is something you do often and do on big Collections,
then copying is wasting time. If you experience performance problems
with the copy solution, then consider making a new class explicitly for
managing "a mapping from string key to variant data with an ordering
on the keys". This class would contain a normal Collection and a String[],
where the String[] contains all keys in their desired ordering (and you
ignore the ordering that Collection keeps).
You have to keep both data structures in sync through all modifications
that the user makes (e.g. _put, Add, Remove, any other methods you add),
but if you manage that, you can add your own API to modify a key (inside
the String[]) without affecting its ordering because the algorithms in
your class will always consult the String[] for the ordering of its keys.
This will use more memory because you effectively store all the keys
once more in the String[], but changing a key will be vastly faster than
to recreate the whole Collection. It all depends on how large your data
is and how frequently you expect to have to change keys.
Best,
Tobias
--
"There's an old saying: Don't change anything... ever!" -- Mr. Monk
More information about the User
mailing list