In depth understanding of the JavaScript series (35) : iterator pattern details for design patterns

  • 2020-05-10 17:40:41
  • OfStack

introduce

Iterator pattern (Iterator) : provides a way to sequence the elements of an aggregated object without exposing the object's internal representation.

Several features of iterators are:

1. Access the content of an aggregate object without exposing its internal representation.
2. Provide a unified 1 interface for traversing different set structures, so as to support the same algorithm to operate on different set structures.
3. Changing the collection structure where the iterator is located while traversing may cause problems (e.g., item is not allowed in foreach of C#).

The body of the

1 like iteration, we should have at least two methods, hasNext() and Next(), so as to traverse all the objects. Let's give an example first:


var agg = (function () {
    var index = 0,
    data = [1, 2, 3, 4, 5],
    length = data.length;     return {
        next: function () {
            var element;
            if (!this.hasNext()) {
                return null;
            }
            element = data[index];
            index = index + 2;
            return element;
        },         hasNext: function () {
            return index < length;
        },         rewind: function () {
            index = 0;
        },         current: function () {
            return data[index];
        }     };
} ());

The usage is the same as it is in C# :

// The results of the iteration are: 1,3,5
while (agg.hasNext()) {
    console.log(agg.next());
}

You can, of course, reset the data in an additional way, and then proceed to do something else:

// reset
agg.rewind();
console.log(agg.current()); // 1

jQuery application example

A very famous iterator in jQuery is the $.each method. Through each, we can pass in additional function, and then iterate over all the item items, such as:


$.each(['dudu', 'dudu', ' Yogurt kid sister ', ' the MM'], function (index, value) {
    console.log(index + ': ' + value);
});
// or
$('li').each(function (index) {
    console.log(index + ': ' + $(this).text());
});

conclusion

Iterators can be used in situations where the results within a collection often vary, and we don't want to expose the internal structure of the collection, but let the client code transparently access the elements.


Related articles: