Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to code iterator in javascript

I'm building a complex object in Javascript and I want to expose an iterator over an internal collection of the object.

The only way I can think of is the usual way of exposing iterators in prototype.js :

customObject.each(function (item) { ... })

with the provided function being called by the iterator each for every item in the collection, one after the other.

Do you know any other reliable way? Maybe a way that would let users use the usual foreach construct?

like image 676
Alsciende Avatar asked Oct 15 '09 10:10

Alsciende


2 Answers

The prototype style function is a good option, though you might also consider something like:

overlayRegistry = function() {
var overlays = [];
var index = 0;


return {
    addOverlay : function(overlay) {
            overlays.push(overlay);
    count : function() {
        return overlays.length;
    },
    reset : function() {
        index = 0;
    },
    next : function() {
        if (index < overlays.length) {
            return overlays[index++];
        } else {
            return null;
                    }
    },
    each : function (callback) {
        for (var index = 0, length = overlays.length; index < length; ++index) {
             callback(overlays[index]);
        }
    }

}
}();

In this case, you can iterate over it in steps while you wait for other events (as was the case behind this structure)

Basically, providing a method like each can work great if all you need is simple iteration, but if you need more control, then something like the above would work (of course, you could do both)

Edit
Added each method

like image 171
Jonathan Fingland Avatar answered Sep 26 '22 02:09

Jonathan Fingland


You should use for in instead.

>>> var customObject = {x: 1, y:2}
>>> for (a in customObject) console.log(a, customObject[a])
x 1
y 2

But remember about inherited properties.

>>>Object.prototype.yarrr = function yarrr(){ console.warn('YARRR!') }
>>> for (a in customObject) console.log(a, customObject[a])
x 1
y 2
yarrr()
>>> for (a in customObject) if (customObject.hasOwnProperty(a)) console.log(customObject[a])
x 1
y 2
like image 45
NVI Avatar answered Sep 26 '22 02:09

NVI