Home > JavaScript | Tech > Visitor and Iterator pattern in JavaScript

Visitor and Iterator pattern in JavaScript

最近また実験的なアプリを JavaScript で書いているんですが、node walker を書く必要にかられ、デザインパターン入門をまた開いてみました。以下のページを開いて、Firebug の console で、例えば window.d = new DOMNodeDest(document.body); d.accept(new Visitor()); などとすれば、各ノードを列挙してくれます。

Viistor Pattern

実際、頭を悩ましたのは、Visitor パターンというより、むしろ Iterator パターンでした。結構面白いと思うんですけど、どうでしょう?

Iterator = function (obj) {
  var i, chld, len, pub, mth,
      result  = {},
      BIND    = Iterator.bind;
  if (obj instanceof Array) {
    this.children = obj;
  }
  else if (typeof(obj) === 'object' && obj !== null) {
    this.children = [];
    chld = this.children;
    for (i in obj) {
      if (obj.hasOwnProperty(i)) {
        chld[chld.length] = obj[i];
      }
    }
  }

  pub = Iterator.publics;
  for (i = 0, len = pub.length; i < len; ++i) {
    mth = pub[i];
    result[mth] = BIND(this[mth], this);
  }
  return result;
};

Iterator.publics = ['next', 'hasNext', 'rewind'];
Iterator.prototype.index    = -1;
Iterator.prototype.children = null;

Iterator.prototype.next = function () {
  if (this.children === null) {
    return null;
  }
  var CHLD    = this.children,
      len     = CHLD.length,
      result  = null;
  ++this.index;
  if (len !== 0 && this.index < len) {
    result = CHLD[this.index];
  }
  return result;
};

Iterator.prototype.hasNext = function () {
  if (this.children === null) {
    return false;
  }
  var result  = false,
      len     = this.children.length;
  if (len !== 0 && this.index < (len - 1)) {
    result = true;
  }
  return result;
};

Iterator.prototype.rewind = function () {
  this.index = -1;
  var it,
      i     = 0,
      CHLD  = this.children,
      len   = CHLD.length;
  if (len) {
    for (;i < len; ++i) {
      it = CHLD[i].iterator;
      if (it) {
        it.rewind();
      }
    }
  }
};

Iterator.bind = function (func, context) {
  return function () {
    return func.apply(context, arguments);
  };
};

Comments:0

Comment Form
Remember personal info

Trackbacks:0

Trackback URL for this entry
http://blog.nydd.org/2009/06/visitor-and-iterator-pattern-in-javascript/trackback/
Listed below are links to weblogs that reference
Visitor and Iterator pattern in JavaScript from Vantage Point of Queens

Home > JavaScript | Tech > Visitor and Iterator pattern in JavaScript

Search
Feeds
Meta
Links
Ads!

Return to page top