[Project_owners] how to implement bounded stack in javascript?

Eric H. Jung grimholtz at yahoo.com
Sun Apr 16 18:53:32 EDT 2006


Thanks everyone for the help.

Here's what I am going to use. It's a bounded queue, not a bounded stack. Modified from your input
and

http://jakarta.apache.org/commons/collections/api-release/org/apache/commons/collections/buffer/CircularFifoBuffer.html

Many thanks!
Eric

function BoundedQueue(size) {
  if (size < 1)
    throw "size must be greater than 0";
  this._elements = new Array(size);
  this._maxElements = size;
  this._end = 0;
  this._start = 0;
  this._full = false;
}
BoundedQueue.prototype = {
  get length() {
    var size = 0;
    if (this._end < this._start) {
        size = this._maxElements - this._start + this._end;
    } else if (this._end == this._start) {
       size = (this._full ? this._maxElements : 0);
    } else {
        size = this._end - this._start;
    }
    return size;
  },

  clear : function() {
    this._full = false;
    this._start = 0;
    this._end = 0;
    this._elements.forEach(function(element, index, array) {array[index] = null;});
  },

  add : function(o) {
    if (this.length == this._maxElements) {
      this._remove();
    }
    this._elements[this._end++] = o;
    if (this._end >= this._maxElements) {
      this._end = 0;
    }
    if (this._end == this._start) {
      this._full = true;
    }
  },

  item : function(idx) {
    if (this.length == 0) {
      throw "The buffer is empty";
    }
    return this._elements[idx];
  },

  _remove : function() {
    if (this.length == 0) {
      throw "The buffer is already empty";
    }
    var element = this._elements[this._start];

    if (element) {
      this._elements[this._start++] = null;
      if (this._start >= this._maxElements) {
        this._start = 0;
      }
      this._full = false;
    }
  }  
};


More information about the Project_owners mailing list