3
\$\begingroup\$

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:

  1. 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).
  2. 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
\$\endgroup\$
0

1 Answer 1

7
\$\begingroup\$

This mostly seems like a layer of sugar coating that just adds overhead and doesn't add any improved functionality over what a javascript object already has. The only new functionality I see is keeping track of a length, but this is a lot of extra overhead just for that. The length could be calculated at any time on a plain javascript object.

Here are the analogs to your methods:

var collection = {};

addItem:
    collection[key] = value;

removeItem: 
    delete collection[key]

clear:
    collection = {};

exists:
    if (key in collection)

getItems:
    collection.keys()

getLength:
    collection.keys().length

So, all you're getting out of your implementation is a slightly more efficient length and every other operation is less efficient than just using the native code way of doing it. Is this collection really useful?

There are some older browsers that don't offer the .keys() method, but there's a pretty simple shim that implements it if not available.

In addition, your implementation loses functionality that a plain javascript object has. For example, you can't pass your collection to any function that expects a javascript object with the keys and values on it because those are hidden inside, they aren't actually properties of the collection object itself. Then further, you can't do custom iteration of the keys and values without first creating an array of all the keys because you've hidden the natural ability to iterate the keys of a javascript object.

\$\endgroup\$
2
  • \$\begingroup\$ @jsfriend00, Thanks ... I agree with you, but are there any disadvantage over using object instead of an array for storing items internally? \$\endgroup\$
    – JeeZ
    Commented Jan 20, 2012 at 6:42
  • 1
    \$\begingroup\$ @JeeZ - Arrays and Objects each have different advantages and disadvantages. Arrays have a defined order - Objects do not. Arrays have a built-in length - Objects do not. Objects have a fast lookup by key - Arrays do not. Objects accept a string as indexes into the data structure - Arrays accept sequential numbers as indexes into the array. An Array can also have object-like properties - An Object does not have Array-like properties. They are different data types with many differences. One should select the type most appropriate to the task at hand. I regularly use both. \$\endgroup\$
    – jfriend00
    Commented Jan 20, 2012 at 6:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.