merge: Refactor Code and Add test case (#845)

This commit is contained in:
YATIN KATHURIA
2021-11-25 10:18:26 +05:30
committed by GitHub
parent 2ae00a97dc
commit 4aac366694
2 changed files with 67 additions and 16 deletions

View File

@ -5,49 +5,52 @@
* implementation uses an array to store the queue. * implementation uses an array to store the queue.
*/ */
// Functions: enqueue, dequeue, peek, view, length // Functions: enqueue, dequeue, peek, view, length, empty
class Queue {
const Queue = (function () {
// constructor // constructor
function Queue () { constructor () {
// This is the array representation of the queue // This is the array representation of the queue
this.queue = [] this.queue = []
} }
// methods // methods
// Add a value to the end of the queue // Add a value to the end of the queue
Queue.prototype.enqueue = function (item) { enqueue (item) {
this.queue.push(item) this.queue.push(item)
} }
// Removes the value at the front of the queue // Removes the value at the front of the queue
Queue.prototype.dequeue = function () { dequeue () {
if (this.queue.length === 0) { if (this.empty()) {
throw new Error('Queue is Empty') throw new Error('Queue is Empty')
} }
const result = this.queue[0] return this.queue.shift() // remove the item at position 0 from the array and return it
this.queue.splice(0, 1) // remove the item at position 0 from the array
return result
} }
// Return the length of the queue // Return the length of the queue
Queue.prototype.length = function () { length () {
return this.queue.length return this.queue.length
} }
// Return the item at the front of the queue // 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] return this.queue[0]
} }
// List all the items in the queue // 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) output(this.queue)
} }
return Queue // Return Is queue empty ?
}()) empty () {
return this.queue.length === 0
}
}
export { Queue } export { Queue }

View File

@ -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()
})
})