The JavaScript STL (Standard Template Library). Part 2 | 2

The JavaScript STL (Standard Template Library). Part 2

The deque collection

The deque is almost identical to the vector but with the added advantage of being able to add and remove elements from the front end efficiently.

function STDDeque()
{
  this.data = new Array();
  this.nBegin = 0;
  this.nEnd = 0;
  this.type = "deque";
 
  // add a few specializations...
  this.push_front = STDDeque_push_front;
  this.pop_front = STDDeque_pop_front;
}
// inherit from STDVector
STDDeque.prototype = STDVector.prototype;

In the code, it "inherits" most of its behaviour from the vector code by redirecting its prototype and then attaching its two extra methods in the constructor:

STDDeque_push_front = function(value)
{
  this.data[--this.nBegin] = value;
}
STDDeque_pop_front = function()
{
  if ( this.nEnd > this.nBegin ) delete this.data[this.nBegin++];
}

The push_front() and pop_front() look very similar to the push_back() and pop_back() methods except that they modify the array's start point.

Demo

Justtechjobs.comFind a programming school near you






Online Campus Both