Created
November 20, 2018 03:32
-
-
Save completejavascript/8f66b9e7a181c0229aba33ad0dc3557d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CQueue { | |
constructor(capacity) { | |
this.data = []; | |
this.capacity = capacity; | |
this.size = 0; | |
this.front = 0; | |
this.rear = 0; | |
} | |
isFull() { | |
return this.size === this.capacity; | |
} | |
isEmpty() { | |
return this.size === 0; | |
} | |
enqueue(item) { | |
if (this.isFull()) return false; | |
this.data[this.rear] = item; | |
this.rear = (this.rear + 1) % this.capacity; | |
this.size++; | |
return true; | |
} | |
dequeue() { | |
if (this.isEmpty()) return undefined; | |
let item = this.data[this.front]; | |
this.front = (this.front + 1) % this.capacity; | |
this.size--; | |
return item; | |
} | |
front() { | |
if (this.isEmpty()) return undefined; | |
return this.data[0]; | |
} | |
rear() { | |
if (this.isEmpty()) return undefined; | |
return this.data[this.size - 1]; | |
} | |
clear() { | |
this.data.length = 0; | |
this.size = 0; | |
this.front = 0; | |
this.rear = 0; | |
} | |
} | |
// Test | |
const Capacity = 5000000; | |
const TestCase = 10; | |
const queue = new CQueue(Capacity); | |
const start = performance.now(); | |
for (let tc = 0; tc < TestCase; tc++) { | |
for (let i = 0; i < Capacity; i++) { | |
queue.enqueue(i); | |
} | |
for (let i = 0; i < Capacity; i++) { | |
queue.dequeue(); | |
} | |
} | |
const end = performance.now(); | |
const duration = (end - start) / TestCase; | |
console.log(`Duration: ${duration} ms`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment