HTML and CSS Reference
In-Depth Information
return index < length;
}
return {
next: next,
hasNext: hasNext
};
}
if (typeof tddjs == "object") {
tddjs.iterator = iterator;
}
}());
The overall pattern should start to look familiar. The interesting parts are the
collection , index and length free variables. The iterator function re-
turns an object whose methods have access to the free variables, and is an imple-
mentation of the module pattern mentioned previously.
The iterator interface was purposely written to imitate that of Java's iter-
ators. However, JavaScript's functions have more to offer, and this interface could
be written in a much leaner way, as seen in Listing 6.23.
Listing 6.23 Functional iterator approach
(function () {
function iterator(collection) {
var index = 0;
var length = collection.length;
function next() {
var item = collection[index++];
next.hasNext = index < length;
return item;
}
next.hasNext = index < length;
return next;
}
if (typeof tddjs == "object") {
tddjs.iterator = iterator;
}
}());
 
Search WWH ::




Custom Search