jsos

college code for operating system fundamentals in js

git clone https://9o.is/git/jsos.git

stack.js

(1409B)


      1 /* ------------
      2    Stack.js
      3    
      4    A simple Stack, which is really just a dressed-up Javascript Array.
      5    See the Javascript Array documentation at http://www.w3schools.com/jsref/jsref_obj_array.asp .
      6    Can be used as a 32-bit memory stack.
      7    
      8    ------------ */
      9 
     10 /* Just a stack. */
     11 function Stack() {
     12   this.q = new Array();
     13 
     14   this.getSize = function(){
     15     return this.q.length;    
     16   }
     17 
     18   this.empty = function() {
     19     return (this.q.length == 0);    
     20   }
     21 
     22   this.push = function(element) {
     23     
     24       this.q.push(element);        
     25   }
     26 
     27   this.pop = function() {
     28     var element = this.peek();
     29     q.pop();
     30     return element;
     31   }
     32   
     33   this.peek = function() {
     34     if(this.getSize() > 0)
     35       return q[this.getSize() - 1];
     36   }
     37     
     38   this.toString = function() {
     39     retVal = "";
     40     for (i in this.q) {
     41       retVal += "[" + this.q[i] + "] ";
     42     }
     43     return retVal;
     44   }    
     45 }
     46 
     47 /*
     48  * A simple stack with a limit. If you pass the limit of 
     49  * maximum bytes, the kernel crashes with a stack overflow.
     50  */
     51 function MemoryStack(maxBytes) {
     52   this.stack = new Stack();
     53 
     54   this.allocateByte = function(byte) {
     55     if(this.stack.getSize() < maxBytes)
     56       this.stack.push(byte);
     57     else
     58       krnTrapError("Stack overflow.")
     59   }
     60 
     61   this.deallocateByte = function() {
     62     this.stack.pop();
     63   }
     64 
     65   this.allocateBytes = function(bytes) {
     66     for (byte in bytes) {
     67       this.allocateByte(byte);
     68     }
     69   }
     70 }