3.6. The Iterator Pattern (ok)

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');
      }
    }
  }
});

Last updated

Navigation

Lionel

@Copyright 2023