I want to implement an ObjectSet class, which contains a set of object references. In the implementation 1 below, I use an Array to store the objects. In the put/remove function, I iterate the whole array to find passed-in object. The set size would be very large and the functions are called frequently. The performance of the iteration is a concern.
In the implementation 2, I use an Object, which acts as a map, to store the object references. In this manner, it doesn't need to iterate all the objects in the put/remove functions. The performance would be better. But the Object property must be a string. I can't use the object as the key. The question is: Is there any algorithm to generate a unique key for an object?
Implementation 1 - Store object references in an Array
function ObjectSet() {
this.store = []; // Array
}
ObjectSet.prototype = {
put: function( obj) {
var store = this.store;
for (var i = 0; i < store.length; i++) {
if (store[i] === obj) {
return;
}
};
},
remove: function( obj ) {
var store = this.store;
for (var i = 0; i < store.length; i++) {
if (store[i] === obj) {
store.splice(i, 1);
}
};
}
};
Implementation 2 - Store object references in an Object
function ObjectSet() {
this.store = {}; // Object
}
ObjectSet.prototype = {
put: function( obj) {
var key = generateKeyFromObject(obj);
if(!this.store[ key ]){
this.store[ key ] = obj;
}
},
remove: function( obj ) {
var key = generateKeyFromObject(obj);
if(this.store[ key ]){
delete this.store[ key ];
}
}
};
function generateKeyFromObject(obj){
// Question: How to generate a unique key for an object?
}
============UPDATE 7/2/2014================
Paste my implementation based on the answers/comments.
// Use the global index to avoid the clash when the same object is added to different sets.
var index = 1, key='##key';
function generateKeyFromObject(obj){
if(!obj[key]){
var uniqueKey="##uniqueKey" + (index++).toString();
Object.defineProperty(obj, key, {
writable: false,
enumerable: false,
configurable: false,
value: uniqueKey
});
}
return obj[key];
}