JavaScript Patterns

Page 167

Iterator In the iterator pattern, you have an object containing some sort of aggregate data. This data may be stored internally in a complex structure, and you want to provide easy access to each element of that structure. The consumer of your object doesn’t need to know how you structure your data; all they need is to work with the individual elements. In the iterator pattern, your object needs to provide a next() method. Calling next() in sequence must return the next consecutive element, where it’s up to you to decide what “next” means in your particular data structure. Assuming that your object is called agg, you could access each data element by simply calling next() in a loop like so: var element; while (element = agg.next()) { // do something with the element ... console.log(element); }

In the iterator pattern, the aggregate object usually also provides a convenience has Next() method, so the users of the object can determine if they’ve reached the end of your data. Another way to access all elements sequentially, this time using hasNext(), would be the like the following: while (agg.hasNext()) { // do something with the next element... console.log(agg.next()); }

Now that we have the use cases, let’s see how to implement such an aggregate object. When implementing the iterator pattern, it makes sense to privately store the data and a pointer (index) to the next available element. To demonstrate a sample implementation, let’s assume the data is just an ordinary array and the “special” logic for retrieval the next consecutive element will be to return every other array element: 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;

Iterator | 149


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.