# 3.6. The Iterator Pattern  (ok)

![](/files/-MTRQst83UiHfapIYwvc)

C:\xampp\htdocs\php\js\main.js

```
require(['iterator/init'],function(init) {
	var examples = {
		iterator: init
	}
	for (var example in examples) {
		examples[example].init();
	}
});
```

C:\xampp\htdocs\php\js\iterator\init.js

```
define(function(require) {
  'use strict';
  return {
    init: function() {
      var iterator = require('iterator/iterator'),
        testArray = [{ something: 'yay', other: 123 }, { something: 'test', other: 456 }],
        myArrayIterator = iterator.build(testArray),
        testString = 'teststring',
        myStringIterator = iterator.build(testString);
      console.log(myArrayIterator.next());
      console.log(myArrayIterator.next());
      while (!myStringIterator.isDone()) {
        console.log(myStringIterator.next());
      }
      console.log(myStringIterator.reset().take(4).join(''));
    }
  };
});
```

C:\xampp\htdocs\php\js\iterator\iterator.js

```
define(function() {
  'use strict';
  var Iterator = function(collection) {
    this.collection = collection;
    this.index = 0;
  };
  Iterator.prototype = {
    constructor: Iterator,
    next: function() {
      return this.collection[this.index++];
    },
    isDone: function() {
      return this.index === this.collection.length;
    },
    reset: function() {
      this.index = 0;
      return this;
    },
    take: function(numberOfItems) {
      var newIndex = this.index + numberOfItems,
        newArr = Array.prototype.slice.call(this.collection, this.index, newIndex);
      this.index = newIndex;
      return newArr;
    }
  };
  return {
    build: function(collection) {
      var keys = Object.keys(collection),
        tempArray = [],
        prop;
      if (typeof collection === 'number') {
        collection = collection.toString();
      }
      if (keys.length) {
        for (prop in collection) {
          tempArray.push(collection[prop]);
        }
        collection = tempArray;
      }
      if (collection.length) {
        return new Iterator(collection);
      } else {
        throw ('Iterator cannot be built from Boolean, null or undefined');
      }
    }
  }
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/advanced/3.6.-the-iterator-pattern-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
