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?
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
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