A Pen by Dave Campion

Thumbnail
This awesome code was written by gasolinewaltz, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright gasolinewaltz ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>A Pen by  Dave Campion</title>
  
  
  
  
  
</head>

<body>

  
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/gasolinewaltz/a-pen-by-dave-campion-wpKYXE */
let SetOfStacks = function(threshold){
  this.stacks = [[]];
  this.threshold = threshold;
}

SetOfStacks.prototype = {
  
  push(val){
    
    let stackIdx = this.stacks.length-1;
    let currentStack = this.stacks[ stackIdx ];
    if( currentStack.length === this.threshold ){
      this.stacks.push( [] );
      stackIdx += 1;
      currentStack = this.stacks[ stackIdx ];
    }
    
    currentStack.push( val );
    
    
  },
  
  pop(){
    
    let stackIdx = this.stacks.length-1;
    let currentStack = this.stacks[ stackIdx ];
    let value = currentStack.pop();
    if( currentStack.length === 0 && this.stacks.length > 1 ){
      this.stacks.pop();
    }
    
    return value;
    
  },
  
  popAt( index ){
    let value = undefined;
    
    if( typeof this.stacks[index] !== undefined ){
      value = this.stacks[index].pop();
      if(this.stacks[index].length === 0 && this.stacks.length > 1){
        this.stacks.splice(index, 1);
      }
    }
    
    return value;
    
  },
  
  print(){
    console.log( this.stacks );
  }
  
}


let stacks = new SetOfStacks( 2 );

console.clear();
stacks.push( 1 );
stacks.print();
stacks.push( 2 );
stacks.push( 3 );
stacks.push( 4 );
stacks.push( 5 );
stacks.print();
console.log( stacks.pop() );
stacks.print();
console.log( stacks.popAt(0));
stacks.print();
console.log( stacks.popAt(1));
stacks.print();
console.log( stacks.pop() );
stacks.print();
console.log( stacks.pop() );
stacks.print();
console.log( stacks.pop() );
stacks.print();

Comments