Skip to content

Commit

Permalink
merge: Refactor Code and Add test case (TheAlgorithms#845)
Browse files Browse the repository at this point in the history
  • Loading branch information
Yatin-kathuria authored Nov 25, 2021
1 parent 2ae00a9 commit 4aac366
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 16 deletions.
35 changes: 19 additions & 16 deletions Data-Structures/Queue/Queue.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,49 +5,52 @@
* implementation uses an array to store the queue.
*/

// Functions: enqueue, dequeue, peek, view, length

const Queue = (function () {
// Functions: enqueue, dequeue, peek, view, length, empty
class Queue {
// constructor
function Queue () {
constructor () {
// This is the array representation of the queue
this.queue = []
}

// methods
// Add a value to the end of the queue
Queue.prototype.enqueue = function (item) {
enqueue (item) {
this.queue.push(item)
}

// Removes the value at the front of the queue
Queue.prototype.dequeue = function () {
if (this.queue.length === 0) {
dequeue () {
if (this.empty()) {
throw new Error('Queue is Empty')
}

const result = this.queue[0]
this.queue.splice(0, 1) // remove the item at position 0 from the array

return result
return this.queue.shift() // remove the item at position 0 from the array and return it
}

// Return the length of the queue
Queue.prototype.length = function () {
length () {
return this.queue.length
}

// Return the item at the front of the queue
Queue.prototype.peek = function () {
peek () {
if (this.empty()) {
throw new Error('Queue is Empty')
}

return this.queue[0]
}

// List all the items in the queue
Queue.prototype.view = function (output = value => console.log(value)) {
view (output = value => console.log(value)) {
output(this.queue)
}

return Queue
}())
// Return Is queue empty ?
empty () {
return this.queue.length === 0
}
}

export { Queue }
48 changes: 48 additions & 0 deletions Data-Structures/Queue/test/Queue.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Queue } from '../Queue'

describe('Queue', () => {
it('Check enqueue/dequeue', () => {
const queue = new Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(8)
queue.enqueue(9)

expect(queue.dequeue()).toBe(1)
expect(queue.dequeue()).toBe(2)
})

it('Check length', () => {
const queue = new Queue()

queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(8)
queue.enqueue(9)

expect(queue.length()).toBe(4)
})

it('Check peek', () => {
const queue = new Queue()

queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(8)
queue.enqueue(9)

expect(queue.peek()).toBe(1)
})

it('Check empty', () => {
const queue = new Queue()
expect(queue.empty()).toBeTruthy()

queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(8)
queue.enqueue(9)

expect(queue.empty()).toBeFalsy()
})
})

0 comments on commit 4aac366

Please sign in to comment.