tags:

views:

58

answers:

2

I'm using python for my shopping cart class which has a list of items. When a customer wants to edit an item, I need to pass the JavaScript front-end some way to refer to the item so that it can call AJAX methods to manipulate it.

Basically, I need a simple way to point to a particular item that isn't its index, and isn't a reference to the object itself.

I can't use an index, because another item in the list might be added or removed while the identifier is "held" by the front end. If I were to pass the index forward, if an item got deleted from the list then that index wouldn't point to the right object.

One solution seems to be to use UUIDs, but that seems particularly heavyweight for a very small list. What's the simplest/best way to do this?

+3  A: 

Instead of using a list, why not use a dictionary and use small integers as the keys? Adding and removing items from the dictionary will not change the indices into the dictionary. You will want to keep one value in the dictionary that lets you know what the next assigned index will be.

Adam Crossland
Where do the keys come from?
FogleBird
@FogleBird: edited my answer to answer your question, I think. When you init your dict, create a special element that holds the next number to be assigned.
Adam Crossland
If you're using a dictionary, you might as well make the keys be UUID's. Then you don't need to maintain a counter variable. Sure the keys are bigger but who cares? It's simpler.
FogleBird
And the UUID would be unique across all shopping carts, in case that ever became useful.
FogleBird
It seems like better practice to keep the ids only unique in scope for that one shopping cart. Doesn't the alternative invite a structure where people could access other people's carts?
colinmarc
I guess that we -- supposedly -- live in an age in which number of bytes don't matter except across vast scales, but I'd always pick one or two bytes over 16 to serve the same purpose.
Adam Crossland
+2  A: 

A UUID seems perfect for this. Why don't you want to do that?

Do the items have any sort of product_id? Can the shopping cart have more than one of the same product_id, or does it store a quantity? What I'm getting at is: If product_id's in the cart are unique, you can just use that.

FogleBird