WaBis

walter.bislins.ch

JavaScript: HistoryStack

Einfacher Stack zum Speichern und Abrufen mehrere Werte z.B. für Eingabefelder.

Anwendung

Die Funktionen SaveToStream und LoadFromStream verwenden den SerializerParser.

Code

function HistoryStack( max ) {
  max = xDefNum( max, 0 );
  this.Stack = [];
  this.MaxSize = max;
  this.SP = 0;
}

HistoryStack.prototype.Push = function( s ) {
  // if s is not in stack, pushes s in front of stack.
  // if s is in stack, it is moved to the front if not already there
  // note: size of stack may be limited, empty string it not pushed to stack
  // returns true if stack is modified
  this.SP = 0;
  if (s == '') return false;
  var p = this.Stack.indexOf( s );
  if (p == 0) return false;
  if (p > 0) {
    this.Stack.splice( p, 1 );
    this.Stack.unshift( s );
  } else {
    var size = this.Stack.unshift( s );
    if (this.MaxSize > 0 && size > this.MaxSize) this.Stack.splice( size-1, 1 );
  }
  return true;
}

HistoryStack.prototype.GetNext = function( oldStr ) {
  // returns next string in stack (or '' if none) not equal oldStr. rolls stack pointer + 1
  var size = this.Stack.length;
  if (size == 0) return '';
  var p = this.SP % size;
  var s = this.Stack[p];
  if (s == oldStr) {
    if (size == 1) return '';
    p = (p+1) % size;
    s = this.Stack[p];
  }
  this.SP = (p+1) % size;
  return s;
}

HistoryStack.prototype.GetPrev = function( oldStr ) {
  // returns previous string in stack (or '' if none) not equal oldStr. rolls stack pointer - 1
  var size = this.Stack.length;
  if (size == 0) return '';
  this.SP = (this.SP + size - 1) % size;
  if (this.Stack[this.SP] == oldStr) {
    if (size == 1) return '';
    this.SP = (this.SP + size - 1) % size;
  }
  return this.Stack[this.SP];
}

HistoryStack.prototype.SaveToStream = function( stream ) {
  return stream.PushStrList( this.Stack );
}

HistoryStack.prototype.LoadFromStream = function( stream ) {
  this.Stack = stream.GetStrList();
  this.SP = 0;
}

Weitere Infos zur Seite
Erzeugt Freitag, 9. Januar 2015
von wabis
Zum Seitenanfang
Geändert Freitag, 9. Januar 2015
von wabis