prototype/src/lang/range.js

75 lines
2.1 KiB
JavaScript
Raw Normal View History

2009-03-05 19:56:01 +00:00
/** section: Language
2008-12-14 04:36:59 +00:00
* class ObjectRange
*
* Ranges represent an interval of values. The value type just needs to be
* "compatible" that is, to implement a `succ` method letting us step from
* one value to the next (its successor).
*
* Prototype provides such a method for [[Number]] and [[String]], but you
* are (of course) welcome to implement useful semantics in your own objects,
* in order to enable ranges based on them.
*
* `ObjectRange` mixes in [[Enumerable]], which makes ranges very versatile.
* It takes care, however, to override the default code for `include`, to
* achieve better efficiency.
*
* While `ObjectRange` does provide a constructor, the preferred way to obtain
* a range is to use the [[$R]] utility function, which is strictly equivalent
* (only way more concise to use).
2008-12-14 04:36:59 +00:00
**/
2009-03-05 19:56:01 +00:00
/** section: Language
2008-12-14 04:36:59 +00:00
* $R(start, end[, exclusive = false]) -> ObjectRange
*
* Creates a new ObjectRange object.
2009-02-24 02:35:49 +00:00
* This method is a convenience wrapper around the [[ObjectRange]] constructor,
2008-12-14 04:36:59 +00:00
* but $R is the preferred alias.
**/
2008-09-29 21:07:16 +00:00
function $R(start, end, exclusive) {
return new ObjectRange(start, end, exclusive);
}
var ObjectRange = Class.create(Enumerable, (function() {
2008-12-14 04:36:59 +00:00
/**
* new ObjectRange(start, end[, exclusive = false])
*
2009-02-24 02:35:49 +00:00
* Creates a new `ObjectRange`.
*
* The `exclusive` argument specifies whether `end` itself is a part of the
* range.
2008-12-14 04:36:59 +00:00
**/
2008-09-29 21:07:16 +00:00
function initialize(start, end, exclusive) {
2007-01-18 22:24:27 +00:00
this.start = start;
this.end = end;
this.exclusive = exclusive;
2008-09-29 21:07:16 +00:00
}
2007-01-18 22:24:27 +00:00
2008-09-29 21:07:16 +00:00
function _each(iterator) {
2007-01-18 22:24:27 +00:00
var value = this.start;
while (this.include(value)) {
iterator(value);
value = value.succ();
}
2008-09-29 21:07:16 +00:00
}
2008-12-14 04:36:59 +00:00
/**
* ObjectRange#include(value) -> Boolean
*
* Determines whether the value is included in the range.
**/
2008-09-29 21:07:16 +00:00
function include(value) {
if (value < this.start)
return false;
if (this.exclusive)
return value < this.end;
return value <= this.end;
}
2008-09-29 21:07:16 +00:00
return {
initialize: initialize,
_each: _each,
include: include
};
})());
2007-01-18 22:24:27 +00:00