In: Computer Science
Problem 3
Prototype object doubleQ
A doubleQ object has 2 instance variables: firstQ and secondQ
arrays that together implement a queue
enqueue() instance method adds its argument to the end of this.secondQ
dequeue() instance method removes and returns the element at the front of this.firstQ
transfer() instance method removes the element from the front of this.secondQ, adds it to the end of this.firstQ
If this.secondQ is empty, does nothing
Test code is included in the file
Download this file (with fragments missing)
Hint: Use the push() and shift()
Listing
<html>
<head>
<title>Assignment 3, Problem 3</title>
<script type="text/Javascript">
function doubleQ( q1, q2 )
{
this.firstQ = q1 || [];
this.secondQ = q2 || [];
this.enqueue = function( item )
{ }; // Code missing
this.dequeue = function()
{ }; // Code missing
this.toString = function()
{ return "[" + this.firstQ + "] ["
+ this.secondQ + "]"; };
}
function doubleQ_transfer()
{
// Code missing
}
doubleQ.prototype.transfer = doubleQ_transfer;
var dQ = new doubleQ( [1, 2], [3, 4] );
document.write( "<p>dQ: " + dQ + "</p>" );
dQ.transfer()
document.write( "<p>After transfer: " + dQ + "</p>" );
document.write( "<p>Value dequeued: " + dQ.dequeue() + "</p>" );
document.write( "<p>After dequeue: " + dQ + "</p>" );
dQ.enqueue(5);
document.write( "<p>After enqueuing 5: " + dQ + "</p>" );
</script>
</head>
<body>
</body>
</html>
Output
dQ: [1,2] [3,4]
After transfer: [1,2,3] [4]
Value dequeued: 1
After dequeue: [2,3] [4]
After enqueuing 5: [2,3] [4,5]
Below is the solution with output screenshot
Code :
<html>
<head>
<title>Assignment 3, Problem 3</title>
<script type="text/Javascript">
function doubleQ(q1, q2) {
this.firstQ = q1 || [];
this.secondQ = q2 || [];
this.enqueue = function(item) {
this.secondQ.push(item);
}; // Code missing
this.dequeue = function() {
return this.firstQ.shift();
}; // Code missing
this.toString = function() {
return "[" + this.firstQ + "] [" + this.secondQ + "]";
};
}
function doubleQ_transfer() {
// Code missing
this.firstQ.push(this.secondQ.shift());
}
doubleQ.prototype.transfer = doubleQ_transfer;
var dQ = new doubleQ([1, 2], [3, 4]);
document.write("<p>dQ: " + dQ + "</p>");
dQ.transfer()
document.write("<p>After transfer: " + dQ + "</p>");
document.write("<p>Value dequeued: " + dQ.dequeue() + "</p>");
document.write("<p>After dequeue: " + dQ + "</p>");
dQ.enqueue(5);
document.write("<p>After enqueuing 5: " + dQ + "</p>");
</script>
</head>
<body>
</body>
</html>
Output :