views:

31

answers:

1

What would be the best way to create an array that can have an index and a key at the same time ?

i mean something like this

index     | key           | value
0         | "myItem"      | "Some value"
1         | "anotherItem" | "Some other value"
2         | "blabla"      | "Bla Bla"

I know i can create a normal Array/Vector and then use an Object/Dictionary to map the keys to the index in the current array.

But if the array changes then the Dictionary needs to change all the indexes that would have been affected because an item has been removed for example. I can go ahead and create a class that tries to synchronize the map with the array etc... But i dont think it is the best way of doing it at all... :)

I wanna use it to have a list... that holds queued items for example. You should be able to get a particular item by its key :

item = list["myItem"]

But you should also be able to find out the index of an item, they have to be ordened , and it should be possible to loop through it as a normal array.

What would be the best way to do something like this in as3 ?

+1  A: 

You say you don't want to have a reverse index for the keys, so I don't see how you could achieve what you are after other than having a function that does a linear search in the array and finds an item given an id.

This assumes your items have a value but also an id: {value:"someValue, id="myItem"}.

A linear search is not a bad idea anyway, unless you have lots of items in your queue and retrieve them by id very often (specially in a tight loop).

Now, if you want to go all the way, you can extend Array functionality by extending the Proxy class to make index / id access transparent (that is, your code would get items with queue[0] or queue['myItem']). You'd still have to synchronize the items internally if you have a reverse index or you could just look them up dinamically (with a linear search).

Check out this answer for pointers on how to do this: http://stackoverflow.com/questions/2080145/extending-as3s-array-access-operators-to-wrap-out-of-bound-index-values/2081531#2081531

Juan Pablo Califano
yes, that is actually what i am doing right now, a class that extends Proxy class , it keeps a reverse index.i was just wondering if there wasnt a better way to do it.i guess not... ;) thx for the answer !
Aaike