1+ /* Queue
2+ * A Queue is a data structure that allows you to add an element to the end of
3+ * a list and remove the item at the front. A queue follows a "First In First Out"
4+ * system, where the first item to enter the queue is the first to be removed. This
5+ * implementation uses an array to store the queue.
6+ */
7+
8+ //Functions: enqueue, dequeue, peek, view, length
9+
10+ var Queue = function ( ) {
11+
12+ //This keeps track of where the end of the queue is
13+ this . back = 0 ;
14+ //This is the array representation of the queue
15+ this . queue = { } ;
16+
17+ //Add a value to the end of the queue
18+ this . enqueue = function ( item ) {
19+ this . queue [ this . back ] = item ;
20+ this . back ++ ;
21+ }
22+
23+ //Removes the value at the front of the queue
24+ this . dequeue = function ( ) {
25+ if ( this . back === 0 ) {
26+ return "Queue is Empty" ;
27+ }
28+
29+ var result = this . queue [ this . front ] ;
30+ delete this . queue [ this . front ] ;
31+
32+ //Shift all the other items forward
33+ for ( var i = 1 ; i < this . back ; i ++ ) {
34+ this . queue [ i - 1 ] = this . queue [ i ] ;
35+ }
36+
37+ //clean up the leftover duplicated value at the back of the queue
38+ delete this . queue [ this . back ] ;
39+ this . back -- ;
40+
41+ return result ;
42+ }
43+
44+ //Return the length of the queue
45+ this . length = function ( ) {
46+ return this . back ;
47+ }
48+
49+ //Return the item at the front of the queue
50+ this . peek = function ( ) {
51+ return this . queue [ 0 ] ;
52+ }
53+
54+ //List all the items in the queue
55+ this . view = function ( ) {
56+ var str = "{"
57+ //construct a single string to represent the items in the queue
58+ for ( var i = 0 ; i < this . back ; i ++ ) {
59+ str += this . queue [ i ] ;
60+ if ( i !== this . back - 1 ) {
61+ str += ", " ;
62+ }
63+ }
64+ str += "}" ;
65+
66+ console . log ( str ) ;
67+ }
68+ }
69+
70+ //Implementation
71+ var myQueue = new Queue ( ) ;
72+
73+ myQueue . enqueue ( 1 ) ;
74+ myQueue . enqueue ( 5 ) ;
75+ myQueue . enqueue ( 76 ) ;
76+ myQueue . enqueue ( 69 ) ;
77+ myQueue . enqueue ( 32 ) ;
78+ myQueue . enqueue ( 54 ) ;
79+
80+ myQueue . view ( ) ;
81+
82+ console . log ( "Length: " + myQueue . length ( ) ) ;
83+ console . log ( "Front item: " + myQueue . peek ( ) ) ;
84+ console . log ( "Removed " + myQueue . dequeue ( ) + " from front." ) ;
85+ console . log ( "New front item: " + myQueue . peek ( ) ) ;
86+ console . log ( "Removed " + myQueue . dequeue ( ) + " from front." ) ;
87+ console . log ( "New front item: " + myQueue . peek ( ) ) ;
88+ myQueue . enqueue ( 55 ) ;
89+ console . log ( "Inserted 55" ) ;
90+ console . log ( "New front item: " + myQueue . peek ( ) ) ;
91+
92+ for ( var i = 0 ; i < 5 ; i ++ ) {
93+ myQueue . dequeue ( ) ;
94+ myQueue . view ( ) ;
95+ }
96+
97+ console . log ( myQueue . dequeue ( ) ) ;
0 commit comments