Skip to content

Instantly share code, notes, and snippets.

@MrThanlon
Created August 9, 2020 09:43
Show Gist options
  • Save MrThanlon/f6853a03b72b7de3b221d48009e3dc11 to your computer and use it in GitHub Desktop.
Save MrThanlon/f6853a03b72b7de3b221d48009e3dc11 to your computer and use it in GitHub Desktop.
Queue.js
const Queue = require('Queue')
const q = new Queue(10)
q.push([1, 2, 3, 4, 5, 6])
q.pop(3) // [1, 2, 3]
q.push([1, 2, 3, 4, 5, 6])
q.pop(5) // [4, 5, 6, 1, 2]
export default class Queue {
constructor(size = 2000) {
this.size = size
this.buffer = new Uint8Array(this.size)
this.first = 0
this.end = 0
this.empty = true
}
/**
* Push buffer to the queue
* @param e {Buffer}
*/
push(e) {
this.empty = false
if (e.length + this.first < this.size) {
if (this.end >= this.first && this.first + e.length >= this.end && (!this.empty)) {
// overflowed
this.end = this.first + e.length
}
this.buffer.set(e, this.first)
this.first += e.length
} else {
// overflowed
this.buffer.set(e.slice(0, this.size - this.first), this.first)
this.buffer.set(e.slice(this.size - this.first), 0)
this.first = e.length + this.first - this.size
if (this.end <= this.first) {
this.end = this.first
}
}
}
/**
* Pop back
* @param length
* @return {null|Uint8Array}
*/
pop(length) {
if (this.empty) {
return null
}
if (this.first > this.end) {
if (this.end + length <= this.first) {
this.end += length
this.empty = this.end === this.first
return this.buffer.slice(this.end - length, this.end)
}
return null
}
// end >= first
if (this.end + length - this.size <= this.first) {
const end = this.end
if (this.end + length < this.size) {
this.end += length
return this.buffer.slice(end, this.end)
}
this.end = (this.end + length) % this.size
this.empty = this.end === this.first
return Uint8Array.concat([this.buffer.slice(end), this.buffer.slice(0, this.end)])
}
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment