ObjectRange类

ObjectRange类提供了对Number和String的$R()方法,非常实用,下面贴出其实现


ObjectRange = Class.create();
   Object.extend(ObjectRange.prototype, Enumerable);//添加了Enumerable扩展
   Object.extend(ObjectRange.prototype, {
       initialize: function(start, end, exclusive) {
           this.start = start;
           this.end = end;
           this.exclusive = exclusive;
       },

    _each: function(iterator) {
           var value = this.start;
           while (this.include(value)) {
                  iterator(value);
                  value = value.succ();//succ()方法不仅使用于Mumber还适用于字符,参见Number.html
             }
       },

include: function(value) {
        if (value < this.start)
              return false;
        if (this.exclusive)
              return value < this.end;
      return value <= this.end;
      }
});

var $R = function(start, end, exclusive) {
          return new ObjectRange(start, end, exclusive);
}

ObjectRange类的each(),include()

$R(1,5,true).each(function (n){alert(n);});

$A($R('a','e'))
//->['a','b','c','d','e']

$A($R('ax','ba'))
//->很大的数组['ax','ay','az','a{','a|','a}','a~'...]

$R(1,10).include(5)
//->true
$R('a','h').include('x')
//->false
$R(1,10).include(10)
//->true
$R(1,10,true).include(10)
//->false