Search code examples
javascriptarraysprivate-members

Read Only Collection or Iterator in JavaScript


I have a small question in regard to JS. It's similar to this post: here from @ADC, with a small caveat.

in his code he creates a java script object:

var AssocArray = function(){
    var collection = new Object();

    this.add = function(id, o){
        collection[id] = o;
    }

    this.remove = function(id){
        delete collection[id];
    }

    this.getById = function(id){
        return collection[id];
    }

    this.get = function(){
        var res = collection;
        return res;
    }
}

Which is something very close to what I need to do. His question was to create a read only property for the get() accessor, which he tackled with cloning the collection private variable.

My problem is that I don't want to create just a clone. What I need is to give the individual elements to the consumer, but prevent them from adding any new ones from the array returned by the get() member. Instead they should use the add(id, o) member to add new items, rather than having the option to add new stuff to the clone returned by the get().

Is that even possible? Is it possible to create or return just an iterator of the collection variable preventing the users to modify the array other than to use the Add/Remove members?


Solution

  • Well, it would be easy enough to create your own iterator:

    this.iterator = function() {
        var n = 0;
        return {
            next: function() { return collection[n++]; }
        };
    }
    

    along with other appropriate iterator machinery for resetting, detecting end, etc.

    Or, you could use ES6 iterators:

    this.iterator = function() { return collection.values(); };
    

    Then the consumer can iterate in all the usual ways, including for...of, iterator.next(), etc.