I am pretty new to JavaScript and learning the intricacies of this language. I wanted a unique collection which will overwrite while adding if an item already exists else add. Rest of the behavior should be just like any other collection. I had written the type and its as below. Instead of using an array internally, I have used JavaScript's notion of storing an object as key-value pair to store the items.
My question is, is this implementation valid? Are there any disadvantage with this implementation over using an array internally to hold the collection items instead of an object?
Why I chose objects to store items over array is:
- To avoid iterating through the array while adding an item, so that I don't have to check if objects exists(instead of adding a duplicate).
- To avoid iterating while retrieving or deleting an item.
function isValid(obj) {
return (obj != undefined && obj != null && typeof (obj) != 'undefined');
}
function uniqueCollection() {
var collection = {};
var length = 0;
return {
removeItem: function (item) {
if (isValid(collection[item])) {
delete collection[item];
--length;
}
},
addItem: function (item) {
if (!isValid(collection[item])) {
collection[item] = item;
++length;
}
},
getLength: function () {
return length;
},
clear: function () {
collection = {};
length = 0;
},
exists: function (item) {
if (isValid(collection[item])) {
return true;
}
return false;
},
getItems: function () {
var items = [];
var i = 0;
for (var o in collection) {
if (collection.hasOwnProperty(o)) {
items[i] = o.toString();
i++;
}
}
if (i !== length) {
alert("Error occurred while returning items");
}
return items;
}
};//end of object literal
};//end of function